这是一个用于表示我每天遇到的一类问题的示例,当我使用内容管理系统为大量网页设置
HTML时,我需要根据模型应用CSS的一般方法.我想知道是否有一种非
Javascript方式来解决它.
假设我有一个div类div,它将有1或2个子div.当它有1个孩子div时,那个孩子应该有红色背景;当它有2个子div时,它们应该有蓝色背景:
<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中这样做?也许是一个黑客?
解决方法
好吧,我会塌陷.这是我的解决方案
.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>