我应该在所有相同的元素上重复上课
<ul class='nav'>
<li class='sub-nav'>
...
</li>
<li class='sub-nav'>
...
</li>
...
</ul>
或者我应该后代选择器
.nav > li {...}
我读了这个enter link description here避免后代选择器,但我认为重复是不好的
我该怎么办?
(对不起,我是新手。)
最佳答案
好的,我理解您的需求,而不是重复相同的类来为您的 li
设置样式,使用 descendant
选择器和 child combinator
选择器。 check this example
如果您使用后代选择器意味着它将选择无序列表下方任何位置的任何列表项或您在标记结构中使用的任何元素。
ul.nav{
width:500px;
overflow:visible;
}
/*this one applies into whole li elements which cames under ul.nav*/
ul.nav li{
background:#f8f8f8;
line-height:30px;
list-style:none;
margin-bottom:5px;
position:relative;
}
ul.nav li ul{
position:absolute;
top:0px;
right:0;
width:100px;
z-index:5;
}
如果您使用子组合器选择器意味着它只会选择作为无序列表的直接子项或您在标记结构中使用的任何元素的列表项。这不会影响其子项的无序列表或任何元素
ul.cselctor{
margin-top:50px;
}
/*this one applies into direct childs (li) elements only which cames under ul.nav*/
ul.cselctor > li{
background:#f00;
line-height:30px;
list-style:none;
margin-bottom:5px;
position:relative;
}
ul.cselctor > li ul{
position:absolute;
top:0px;
right:0;
width:100px;
z-index:5;
}
这是针对您在评论中的问题
.nav
如果你单独使用这个类意味着你可以将这个类用于任何东西 div's, a's ,span's
....等等,ul.nav 意味着它仅适用于无序列表..例如.. a.nav{}
此处此导航类仅用于 anchor 元素。该类仅用于相应的元素..
关于css - 后代选择器或在 html 中重复相同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19952887/