CSS选择器ul li a {...} vs ul> li>一个 {...} [英] CSS selectors ul li a {...} vs ul > li > a {...}

查看:134
本文介绍了CSS选择器ul li a {...} vs ul> li>一个 {...}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. ul> li> CSS中的{...} ul li a {...}

  2. 一个更高效,为什么?


解决方案

/ code>是子选择器 p>

后代选择器



不同之处在于后代可以是元素的子元素,子元素的子元素或子元素的子元素



子元素只是一个直接包含在父元素中:

 < foo> <! -  parent  - > 
< bar> <! - foo的孩子,foo的后裔 - >
< baz> <! - foo的后代 - >
< / baz>
< / bar>
< / foo>

对于此示例, foo * < bar> < baz> ,而 foo& * 只会匹配< bar>




哪一个更有效率,为什么?


我实际上不会回答这个问题,因为它与开发完全无关。 CSS渲染引擎是如此之快,以至于几乎从来没有*优化CSS选择器的理由,使它们尽可能短。



不用担心微优化,焦点写选择器对于手头的情况有意义。在对嵌套列表进行样式化时,我经常使用> 选择器,因为区分列表中的哪个级别是非常重要的。



*如果真的是在渲染页面的问题,你可能有太多的元素在页面上,或太多的CSS。然后你必须运行一些测试,看看实际的问题是什么。


  1. What is the difference between ul > li > a {...} and ul li a {...} in CSS?
  2. Which one is more efficient and why?

解决方案

">" is the child selector

"" is the descendant selector

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>

for this example, foo * would match <bar> and <baz>, whereas foo > * would only match <bar>.

As for your second question:

Which one is more efficient and why?

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.

* if it genuinely is an issue in rendering the page, you've probably got too many elements on the page, or too much CSS. Then you'll have to run some tests to see what the actual issue is.

这篇关于CSS选择器ul li a {...} vs ul&gt; li>一个 {...}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆