html – 根据父级内的计数设置子元素
发布时间:2020-12-14 16:40:37 所属栏目:资源 来源:网络整理
导读:这是一个用于表示我每天遇到的一类问题的示例,当我使用内容管理系统为大量网页设置 HTML时,我需要根据模型应用CSS的一般方法.我想知道是否有一种非 Javascript方式来解决它. 假设我有一个div类div,它将有1或2个子div.当它有1个孩子div时,那个孩子应该有红色
这是一个用于表示我每天遇到的一类问题的示例,当我使用内容管理系统为大量网页设置
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中这样做?也许是一个黑客? 解决方法
好吧,我会塌陷.这是我的解决方案
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 值得至少研究一下.这是一个嵌入式示例. .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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |