我对这个 css 选择器有些困惑。而这段代码的性能好坏。
[class*=thumb] [class*=_child]> * > h3,
[class*=thumb] [class*=_child]>* p,
[class*=sidebar] [class*=gallery] h3 {
height:56px;
overflow:hidden;
margin-top:2px;
font-weight:400;
}
我对这个 css 选择器有些困惑。而这段代码的性能好坏。
[class*=thumb] [class*=_child]> * > h3,
[class*=thumb] [class*=_child]>* p,
[class*=sidebar] [class*=gallery] h3 {
height:56px;
overflow:hidden;
margin-top:2px;
font-weight:400;
}
嗯,第一个选择器首先查找类名中任何位置包含“thumb”的类的任何元素 - 但是我不确定没有引号它会如何执行。下一个选择器也是如此,但使用“_child”字符串,它正在查看前一个选择器的所有子项。然后它继续选择满足这个标准的所有东西(这有时会导致意想不到的问题),然后是这些的所有子 h3。
因此,它看起来是一个极其复杂的布局,其中充满了可能的错误,并且可以通过在 DOM 中添加一个更深的类来简化它。
在性能方面,最好的是 ID,然后是类。在性能方面,拥有基于属性的选择器并不是那么好。此外,如果可以,应避免使用子选择器(带有“>”的选择器)。
无论如何,关键是您编写的代码表现不佳。
此外,这可能会帮助您:
选择器具有内在的效率,引用 Steve Souders 的话,CSS 选择器从高到低的顺序是这样的:
ID, e.g. #header Class, e.g. .promo Type, e.g. div Adjacent sibling, e.g. h2 + p Child, e.g. li > ul Descendant, e.g. ul a Universal, i.e. * Attribute, e.g. [type="text"] Pseudo-classes/-elements, e.g. a:hover
来源:http ://csswizardry.com/2011/09/writing-efficient-css-selectors/
也许您还想阅读以下内容:https ://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
祝你好运!