CSS应用类,其中父级没有类

时间:2016-04-11 19:11:04

标签: html css

这是我想要完成的事情,可能会走错路。

我的页面上的所有按钮都有css

button, input[type=button]{
  background-color: red;
}

目标是将此类应用于网站上的所有按钮,除非该按钮位于具有类" clean"的父级内部。父母可能是夫妻元素更高。

<div>
  <button>Class Applied</button>
</div>

<div class="clean">  <- Parent 1
  <div>  <- Parent 2
    <div>  <- Parent 3
      <button>Class NOT Applied</button>
    </div>
  </div>
</div>

前2个按钮不应该应用样式:http://codepen.io/amstech/pen/PNQQBo

3 个答案:

答案 0 :(得分:0)

将其添加到第一个代码块下方的任意位置,然后为.clean按钮选择所需的样式类型。它应该工作(测试)。

.clean button {
  background-color: white;
}

答案 1 :(得分:0)

这样的东西?

div.clean button { 
    // if parent has clean class
    background-color: red;
}

div:not(.clean) button { 
    // if parent has not clean class
    background-color: white;
}

div.clean div button { 
    // button has any parent div with .clean class
    // and atleast one subparented div
    background-color: red;
}

div.clean div:not(.clean) button { 
    // button has any parent div with .clean class
    // and atleast one subparented div which has not .clean class
    background-color: red;
}

div.clean div div button { 
    // button has any parent div with .clean class
    // and atleast 2 subparented divs, now set the color as white
    background-color: white;
}

答案 2 :(得分:0)

Fiddle

HTML

<div>
  <div class="clean">
    <!--Assume this is a directive and I don't know anything about depth of the element-->
    <div>
      <button>
        1. no class applied
      </button>
    </div>
    <button>
      2. no class applied
    </button>
  </div>
  <!-- and this button is on my site and i have control over it-->
  <button>
    3. class applied
  </button>
</div>

CSS

*:not(.clean) button,
*:not(.clean) input[type=button] {
  background-color: red;
}

*.clean button,
*.clean input[type=button] {
  background-color: initial;
}