2017-08-15 30 views
0

我有以下HTML:多个最后一个孩子没有按预期工作。为什么?

<ul> 
    <li>1</li> 
    <li>2</li> 
    <li>3</li> 
    <li>4</li> 
    <li>5</li> 
    <li>6</li> 
    <li>7</li> 
    <li>8</li> 
    <li>9</li> 
    <li>10</li> 
    <li>11</li> 
    <li>12</li> 
</ul> 

并应用于它下面的CSS:

body { 
    padding: 0; 
    margin: 0; 
    display: flex; 
    align-items:center; 
    justify-content:center; 
    height: 100vh; 
    background: #eee; 
} 

ul { 
    max-width: 400px; 
    min-width: 400px; 
} 

ul > li { 
    overflow: hidden; 
    float: left; 
    width: 30%; 
    height: 50px; 
    margin: 1%; 
    background: orange; 
    color: #fff; 
    display: flex; 
    align-items:center; 
    justify-content:center; 
} 

ul > li:nth-child(3n + 1):nth-last-child(3) { 
    background: #727272; 
} 

你可以看到同样的小提琴HERE

现在以下选择:

ul > li:nth-child(3n + 1):nth-last-child(3) { 
     background: #727272; 
    } 

似乎是在最后一排选择的第一要素,我不是很了解如何?

而且

ul > li:nth-child(3n + 1):last-child { 
     background: #727272; 
    } 

开不工作。为什么?

我INFACT希望以下选择器选择最后一排的第一个元素:

ul > li:nth-child(3n + 1):nth-last-child(1) { 
     background: #727272; 
    } 

那么究竟我是曲解这里是什么,为什么多nth-child选择不工作,我期望它的方式吗?

如何我想实现: 最后一排选择的第一要素..我相信我已经来达到的是,只是不知道它是如何工作的。

+1

为什么'ul> li:nth-​​child(3n + 1):nth-​​last-child(3)'工作是因为':nth-​​last-child(3)'从结尾选择第3个元素,这恰好是最后一行的第一行(和从第一行开始的每隔3个行开始的':nth-​​child(3n + 1)'目标,这又覆盖了最后一行的第一行) – LGSon

回答

2

这..

ul > li:nth-child(3n + 1):nth-last-child(1) { 
     background: #727272; 
    } 

不起作用,因为它不符合条件。

这不是:nth-last-child(1) AND :nth-child(3n+1)所以它没有被选中。

这工作

ul > li:nth-child(3n + 1):nth-last-child(3) { 
     background: #727272; 
    } 

becuasie它既是li:nth-child(3n + 1):nth-last-child(3)

但是,它选择最后一行中的第一个元素的事实是纯粹是巧合。

CSS无法检测布局。它不知道这是连续的。 CSS选择元素而没有别的。

+0

出于某种奇怪的原因,我在想':nth-​​child(3n + 1)'创建一个集合,然后我只做'nnth-last-child(1)',选择集合中的最后一个元素,但我想我错了......那不是css的作品! –

相关问题