html - css 选择器 nth-child - 以第一个 (n) 个 child 为目标

标签 html css

我一直在尝试仅针对使用 css 选择器 nth-child 和/或 nth-last-child 的前四个列表项

<ul>
    <li>Hello first item</li>
    <li>Hello item 2<li>
    <li>Hello item 3</li>
    <li>Hello   item 4</li>
    <li>Hello  item 5</li>
    <li>Hello   item 6</li>
    <li>Hello   item 7</li>
    <li>Hello  item 8</li>
    <li>Hello  item 9</li>
</ul>

我的第一次尝试:

ul li:nth-child(1n):not(:nth-last-child(-n+5)){
    font-weight:bold;
}

但我想简化它

所以我的第二个:

ul li:nth-child(-n+4){
    font-weight:bold;
}

你能告诉我是否有比第二个更好的解决方案/这是针对第一 (n) 个 child 的正确方法吗?

最佳答案

如果您更正拼写错误,您的代码将正常工作:

jsFiddle example

虽然更好的解决方案可能是:

 ul li:nth-child(-n+4) {
     font-weight:bold;
 }

jsFiddle example

关于html - css 选择器 nth-child - 以第一个 (n) 个 child 为目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21140514/

相关文章:

css - flexbox:调整元素大小

html - 根据屏幕大小通过css重新定位html元素

javascript - 如何在视差 slider 中添加视频?

javascript - 单击按钮后显示 javascript 测验

javascript - 创建类似 Twitter 的状态更新小部件的最简单方法

html - 带有标有 aria-label 的图标的按钮仍然是 'Empty Button' 错误

javascript - Css jQuery 蛇尝试

javascript - 具有单像素边框的同位素布局

html - 使用负边距的垂直居中,在 Safari 中有效,但在 Firefox/Chrome 中无效,有什么想法吗?

javascript - 如何通过单击相同的链接从两个不同的 div(来自 html)加载两个 div