我有两个带有“包装器”类的 DIV。 我想对它们进行一般样式设置,并为最后一个赋予特殊样式:
<div class="cont">
<span class="help">
<div class="wrapper">aaaa</div>
</span>
<span class="help">
<div class="wrapper">bbbbb</div>
</span>
</div>
(在我的真实示例中,跨度内有多个 div,因此我需要定位这个特定的类)
我尝试了各种 CSS 规则:
div.wrapper { background:green; }
div.wrapper:last-child{ background:red; }
div > span > div.wrapper { background:green; }
div > span > div.wrapper:last-child{ background:red; }
div .wrapper { background:green; }
div .wrapper:last-child{ background:red; }
什么都没有,有效,甚至没有:
div div { background:green; }
div div:last-of-type { background:red; }
它总是使所有内容都是红色的,就好像每个 DIV 都是最后一个子元素。
最佳答案
:last-child
是相对于父级的,所以这里:
<div class="cont">
<span class="help">
<div class="wrapper">aaaa</div>
</span>
<span class="help">
<div class="wrapper">bbbbb</div>
</span>
</div>
.wrapper
带文字aaaa
是:last-child
第一个 <span>
与类.help
,第二个 .wrapper
带文字bbbbb
也是:last-child
第二个<span>
与类.help
.
您需要申请:last-child
选择.help
相反,它将选择最后一个 .help
,然后使用 descendant或child选择器以 .wrapper
为目标里面:
.help:last-child > .wrapper
如果您还可以有多个.wrapper
内单.help
如果您只想选择最后一个,那么它将是:
.help:last-child > .wrapper:last-child
这是一个例子:
body {
font-family: monospace;
font-size: 16px;
}
.cont {
border: 3px solid #000;
margin: 0 0 3px;
}
.help + .help {
margin: 3px 0 0;
}
.wrapper {
background: #F0F;
padding: 1px 6px;
}
.help:last-child > .wrapper:last-child {
background: #FF0;
}
<div class="cont">
<div class="help">
<div class="wrapper">AAA</div>
</div>
<div class="help">
<div class="wrapper">BBB</div>
</div>
</div>
<div class="cont">
<div class="help">
<div class="wrapper">CCC</div>
</div>
<div class="help">
<div class="wrapper">DDD</div>
</div>
<div class="help">
<div class="wrapper">EEE 1</div>
<div class="wrapper">EEE 2</div>
<div class="wrapper">EEE 3</div>
</div>
</div>
正如您在评论中指出的那样,如果 .cont
中的最后一个元素不是.help
,但是前一项是,这一项(前一项)不会被选中。
最好的选择是使用 :nth-last-child( <nth> [ of <selector># ]? )
:
.help:nth-last-child(1 of .help) > .wrapper:last-child
但支持 Selectors Level 4仍然很低...
具有良好支持的替代方案是使用 :last-of-type
,但它有一个限制:现在,您用于 .help
的元素必须与 .cont
的子级(直系后代)使用的其他不同。 :
body {
font-family: monospace;
font-size: 16px;
}
.cont {
border: 3px solid #000;
margin: 0 0 3px;
}
.help + .help {
margin: 3px 0 0;
}
.foo {
display: block;
background: #0FF;
margin: 3px 0 0;
padding: 1px 6px;
}
.wrapper {
background: #F0F;
padding: 1px 6px;
}
.help:last-of-type > .wrapper:last-child {
background: #FF0;
}
<div class="cont">
<div class="help">
<div class="wrapper">CCC</div>
</div>
<div class="help">
<div class="wrapper">DDD</div>
</div>
<div class="help">
<div class="wrapper">EEE 1</div>
<div class="wrapper">EEE 2</div>
<div class="wrapper">EEE 3</div>
</div>
<!-- Note I'm using a <span> here -->
<span class="foo">Hi there.</div>
</div>
关于css - 为具有特定类别的 div 的最后一个子元素设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598672/