html - 根据列表元素的数量为 li 第一个 child 设置不同的边距

标签 html css css-selectors siblings

<分区>

我正在尝试根据 LI 元素的数量为 UL 中 LI 的第一个元素设置不同的 CSS 边距值。 即

<ul>
 <li> (margin: 20%)
 <li>
 <li>
</ul>

<ul>
 <li> (margin: 40%)
 <li>
</ul>

尝试使用 :nth-last-child(n + 3) 但它不起作用。 有什么建议么? 谢谢

最佳答案

DEMO

styles can be applied to the children nodes based on the number of siblings they have.

html

<ul>
    <li>one item</li>
</ul>

<ul>
    <li>two items</li>
    <li>two items</li>
</ul>

<ul>
    <li>three items</li>
    <li>three items</li>
    <li>three items</li>
</ul>

<ul>
    <li>four items</li>
    <li>four items</li>
    <li>four items</li>
    <li>four items</li>
</ul>

CSS

 li:first-child:nth-last-child(1) {
    margin-left: 0px;
}

li:first-child:nth-last-child(2) ~ li {
    margin-left: 0px;
}

li:first-child:nth-last-child(3) ~ li {
    margin-left: 0px;
}

li:first-child:nth-last-child(4) ~ li {
    margin-left: 0px;
}

 li:first-child:nth-last-child(4) {
     margin-left:10px;
    color:red;
 }

 li:first-child:nth-last-child(3) {
     margin-left:20px;
    color:green;
 }

 li:first-child:nth-last-child(2) {
     margin-left:30px;
    color:blue;
 }

 li:first-child:nth-last-child(1) {
     margin-left:40px;
     color:gray;
 }

引用:Can CSS detect the number of children an element has?

关于html - 根据列表元素的数量为 li 第一个 child 设置不同的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30493434/

相关文章:

javascript - 如何从 Bootstrap 导航栏中删除默认填充

html - 不能给我的 div,宽度 100%

html - 如何在 tr :hover? 中获取 <tr> 上的边界半径

javascript - 在 var 函数中覆盖 jQuery 添加的内联样式

html - 如何在事件选项卡上制作三 Angular 形

jquery - 我如何创建像 Lowes.com 那样的导航系统

html - 了解 CSS 选择器优先级/特异性

css - 有没有办法在 tr 级别通过 css 应用背景颜色?

java - 无法单击 '100' 搜索结果类和 xpath - selenium webdriver java

javascript - 有没有办法将变量从 javascript 导入到 sass,反之亦然?