在内部具有特定元素的元素上设置CSS属性

时间:2012-12-28 02:44:14

标签: html css

我想在element1上应用规则,如果它包含element2。有可能吗?

<element1>

  ...

  <element2> ... </element2>

</element1>

2 个答案:

答案 0 :(得分:3)

不,没有办法设置父元素的样式。在CSS中,没有像&lt; 这样的运算符。您只能使用&gt; 或使用空格分隔的后代为直接子项设置样式。

有关详情,请参阅类似问题Is there a CSS parent selector?

答案 1 :(得分:1)

这只适用于Jquery ,那么你需要使用类似这样的东西

    $("div").each(function(){

            if(jQuery(this).attr('class') != undefined && jQuery(this).hasClass('myclass')) {
              jQuery(this).css({"background-color":"green"});
         } else {
              jQuery(this).css({"background-color":"red"});
         }
    });​