这是一个用于表示我每天遇到的一类问题的示例,当我使用内容管理系统为大量网页设置HTML时,我需要根据模型应用CSS的一般方法.我想知道是否有一种非Javascript方式来解决它.
假设我有一个div类some-div,它将有1或2个孩子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>Run Code Online (Sandbox Code Playgroud)
有没有办法在CSS中这样做?也许是黑客?
Jos*_*kle 10
好吧,我会塌陷.这是我的解决方案
.some-class div {
background: blue;
}
.some-class div:first-child:last-child {
background: red;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
显然,:only-child我还通过调查@LiorRaz的评论找到了选择器
值得至少研究一下.这是一个嵌入式示例.
.some-class div {
background: blue
}
.some-class div:only-child {
background: red;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
你可以用css伪FIDDLE在这里定位div
CSS
.some-class div:only-child
{
background: red;
}
.some-class div:not(:only-of-type)
{
background: blue;
}
Run Code Online (Sandbox Code Playgroud)
对于支持:nth-last-of-type(http://www.w3.org/TR/selectors/#nth-last-child-pseudo)的现代浏览器
.some-class div{
background-color: red;
}
.some-class div + div,
.some-class div:nth-last-child(2){
background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
演示http://jsfiddle.net/gaby/ofhb3hj1/
Hor*_*ray -1
只需为所有您想要红色的类添加一个类,并为所有您想要蓝色的类添加一个单独的类即可。例子:
<div class="some-class">
<div class="red">
<p>The background of this should be red.</p>
</div>
</div>
<div class="some-class">
<div class="blue">
<p>The background of this should be blue.</p>
</div>
<div class="blue">
<p>The background of this should be blue</p>
</div>
</div>
.blue {
background: blue;
}
.red {
background: red;
}
Run Code Online (Sandbox Code Playgroud)