这是一个虚构的例子来代表我每天都遇到的问题,当我使用一个内容管理系统来设置成吨的网页的HTML时,我需要根据样机应用CSS的一般方法。我想知道是否有一种非Javascript的方法来解决这个问题。
假设我有一个some-div类的div,它将有一个或两个子divs。当它有一个子div时,该子div应该有red背景;当它有2个子div时,它们应该有blue背景:
<div class="some-class">
<div>
<p>The background of this should be red.</p>
</div>
</div>
<div class="some-class">
<div>
<p>The background of this should be blue.</p>
</div>
<div>
<p>The background of this should be blue</p>
</div>
</div>
有没有办法在CSS中做到这一点?也许是黑客干的?
发布于 2014-12-25 04:00:50
好吧,我会投降的。这是我的解决方案
http://jsfiddle.net/z7ajmh5z/
.some-class div {
background: blue;
}
.some-class div:first-child:last-child {
background: red;
} <div class="some-class">
<div>
<p>The background of this should be red.</p>
</div>
</div>
<div class="some-class">
<div>
<p>The background of this should be blue.</p>
</div>
<div>
<p>The background of this should be blue</p>
</div>
</div>
编辑
显然,还有我通过查看@LiorRaz's comment找到的:only-child选择器
它有about as much support as :last-child
至少值得一查。这里有一个嵌入的示例。
.some-class div {
background: blue
}
.some-class div:only-child {
background: red;
} <div class="some-class">
<div>
<p>The background of this should be red.</p>
</div>
</div>
<div class="some-class">
<div>
<p>The background of this should be blue.</p>
</div>
<div>
<p>The background of this should be blue</p>
</div>
</div>
https://stackoverflow.com/questions/27641597
复制相似问题