CSS 选择器 ul li a {...} vs ul >李>一个 {...}
ul>有什么区别?李>CSS 中的 {...}
和ul li a {...}
?- 哪个效率更高,为什么?
推荐答案
">
" 是 子选择器
"" 是 后代选择器
区别在于后代可以是元素的子元素,也可以是元素的子元素的子元素,也可以是子元素的子元素的子元素ad inifinitum.
The difference is that a descendant can be a child of the element, or a child of a child of the element or a child of a child of a child ad inifinitum.
子元素只是直接包含在父元素中的元素:
A child element is simply one that is directly contained within the parent element:
<foo> <!-- parent -->
<bar> <!-- child of foo, descendant of foo -->
<baz> <!-- descendant of foo -->
</baz>
</bar>
</foo>
对于这个例子,foo *
将匹配 <bar>
和 <baz>
,而 foo >*
只会匹配 <bar>
.
for this example, foo *
would match <bar>
and <baz>
, whereas foo > *
would only match <bar>
.
关于你的第二个问题:
哪个更高效,为什么?
我实际上不会回答这个问题,因为它与开发完全无关.CSS 渲染引擎的速度如此之快,几乎没有* 优化 CSS 选择器的理由,只需要使它们尽可能短.
I'm not actually going to answer this question as it's completely irrelevant to development. CSS rendering engines are so fast that there is almost never* a reason to optimize CSS selectors beyond making them as short as possible.
与其担心微优化,不如专注于编写对当前案例有意义的选择器.在为嵌套列表设置样式时,我经常使用 >
选择器,因为区分正在设置样式的列表级别很重要.
Instead of worrying about micro-optimizations, focus on writing selectors that make sense for the case at hand. I often use >
selectors when styling nested lists, because it's important to distinguish which level of the list is being styled.
* 如果在渲染页面时确实是一个问题,那么你可能在页面上有太多元素,或者 CSS 太多.然后你必须运行一些测试来看看实际的问题是什么.
相关文章