Apply CSS styles to an element depending on its child elements [duplicate]

10/14 03:38
阅读数 0

问题:

This question already has answers here : 这个问题在这里已经有了答案
Closed 10 months ago . 10 个月前关闭。

Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?是否可以为元素定义 CSS 样式,仅当匹配元素包含特定元素(作为直接子项)时才应用?

I think this is best explained using an example.我认为这最好用一个例子来解释。

Note : I'm trying to style the parent element , depending on what child elements it contains.注意:我正在尝试设置父元素的样式,具体取决于它包含的子元素。

<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>

Note 2 : I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.注 2 :我知道我可以使用 javascript 来实现这一点,但我只是想知道这是否可以使用一些未知的(对我而言)CSS 功能。


解决方案:

参考一: https://en.stackoom.com/question/9lEB
参考二: https://stackoom.com/question/9lEB
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部