【发布时间】:2011-01-20 13:19:13
【问题描述】:
是否可以为元素定义 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 功能。
【问题讨论】:
-
您可能希望更新问题以说明您正在尝试设置 PARENT div 的样式,而不是其子项。我知道信息就在问题本身中,但除非你想得到大量不正确的答案,否则这可能是值得的。
-
谢谢@Seth。我试图改进问题的标题和文字。如果您认为问题仍然不清楚,请编辑问题。
-
这是一个完美的例子,说明为什么 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; }在理想的世界中,这将增加ol的边距,具体取决于li的数量子元素包含在内,这样左边的边距就只有它需要的宽度了。 -
实际上这个功能正在使用 :has 选择器 - bkardell.com/blog/canihas.html