如果匹配的元素包含特定元素(作为直接子项),是否可以定义一个仅适用于该元素的CSS样式?
我认为可以通过示例来最好地解释这一点。
注意:我正在尝试根据父元素所包含的子元素来设置父元素的样式。
<style>
/* note this is invalid syntax. I'm using the non-existing
":containing" pseudo-class to show what I want to achieve. */
div:containing div.a { border: solid 3px red; }
div:containing div.b { border: solid 3px blue; }
</style>
<!-- the following div should have a red border because
if contains a div with class="a" -->
<div>
<div class="a"></div>
</div>
<!-- the following div should have a blue border -->
<div>
<div class="b"></div>
</div>
注意 2: 我知道我可以使用JavaScript来实现这个功能,但我只是想知道是否有一些我不知道的CSS特性可以实现。
ol < li:nth-child(n+10) { margin-left: 2rem; } ol < li:nth-child(n+100) { margin-left: 3rem; } ol < li:nth-child(n+1000) { margin-left: 4rem; }
在理想的情况下,这将根据包含的li
子元素数量增加ol
的边距,以便左侧的边距只有必要时才会变宽。 - Jonmark Weber