首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >根据父元素中的计数对子元素设置样式

根据父元素中的计数对子元素设置样式
EN

Stack Overflow用户
提问于 2014-12-25 03:49:31
回答 5查看 340关注 0票数 7

这是一个虚构的例子来代表我每天都遇到的问题,当我使用一个内容管理系统来设置成吨的网页的HTML时,我需要根据样机应用CSS的一般方法。我想知道是否有一种非Javascript的方法来解决这个问题。

假设我有一个some-div类的div,它将有一个或两个子divs。当它有一个子div时,该子div应该有red背景;当它有2个子div时,它们应该有blue背景:

代码语言:javascript
复制
    <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中做到这一点?也许是黑客干的?

EN

Stack Overflow用户

发布于 2014-12-25 04:00:50

好吧,我会投降的。这是我的解决方案

http://jsfiddle.net/z7ajmh5z/

代码语言:javascript
复制
.some-class div {
    background: blue;
}

.some-class div:first-child:last-child {
    background: red;
}
代码语言:javascript
复制
    <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

至少值得一查。这里有一个嵌入的示例。

代码语言:javascript
复制
.some-class div {
  background: blue
}

.some-class div:only-child {
  background: red;
}
代码语言:javascript
复制
    <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>

票数 10
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27641597

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档