是否可以使用 CSS3 仅使用 CSS 格式化父 div 的子 div,例如:
- 当有 3 个 div 时,在 div 1 和 2 上设置属性 x。
- 当有 2 个 div 时,在 div 1 上设置属性 x
- 当有 1 个 div 时,在 div 1 上不设置属性 x
或者我必须为这个动态逻辑使用 jquery 吗?
最佳答案
.parent div {
height: 1em;
width: 1em;
background: red;
margin: 0.5em;
}
.parent div:last-child {
background: green;
}
<div class="parent">
<div></div>
<div></div>
<div></div>
</div>
<hr />
<div class="parent">
<div></div>
<div></div>
</div>
<hr />
<div class="parent">
<div></div>
</div>
我认为你可以用纯 css 解决你的问题。
想想最后一个 child 选择器:http://www.w3schools.com/cssref/sel_last-child.asp
为所有 child 设置相同的样式,但对最后一个 child 应用不同的样式。
所以在 3 div 的情况下,第三个 div 将获得 last-child 样式 在 2 div 的情况下,第二个 child 将获得 last-child 样式等。
关于jquery - 根据 div 中的元素数使用 css 设置 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28294756/