<分区>
<分区>
ul {
display: inline-block;
list-style: none;
text-align: center;
}
ul::after {
display: table;
content: "";
clear: both;
}
ul:first-child {
background-color: red;
margin-left: 2rem;
}
li {
float: left;
}
<body>
<ul>
<li>House</li>
<li>Dog</li>
</ul>
</body>
通过上面的代码,发现 :first-child 选择器(伪类)不起作用很奇怪。我会假设带有 House
的 li 会有红色背景。相反,没有红色背景。你们知道为什么吗?
最佳答案
您需要将first-child
伪类添加到li
标记,而不是ul
。
li:first-child {
background-color: red;
margin-left: 2rem;
}
根据 MDN documentation它从同一元素的 sibling 中选择第一个元素。
关于html - :first-child selector on cleared element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56414764/