問題描述
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 太多.然后你必須運行一些測試來看看實際的問題是什么.
這篇關于CSS 選擇器 ul li a {...} vs ul >李>一個 {...}的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!