3

Lets say I have the following markup:-

<div class="house">
  <p>...</p>
  <div class="room">
    <p>...</p>
  </div>
</div>

<div class="house">
  <p>...</p>
  <div class="room porch">
     <p>...</p>
  </p>
</div>

CSS:-

.house .room { /* Some styling done here */ }

.porch { /* Some different styling done here */ }

Now, I'd like my div with the classes room and porch to consider only the class porch and ignore the styles of house and room. Is this possible? This is just a simple example, I have a case where in place of the class porch, there are many more classes, so overriding just one class with !important won't work, as there could be a lot of classes with various styles.

How can this be achieved?

4

2 回答 2

5

你可以使用:not

.house .room:not(.porch) { 
      /* .room elements only when they have not .porch class */ 
}

.porch { 
      /* all .porch elements */
}

浏览器支持:https ://developer.mozilla.org/en-US/docs/Web/CSS/:not

于 2013-10-09T15:42:57.493 回答
1

哪个选择器对所选样式规则有效是一个问题。

  1. 样式顺序后面的选择器会覆盖前面的选择器
  2. 具有较高特异性的选择器会否决具有较低特异性的选择器,即使后者排在前者之后

所以制作这个选择器。
. house .room.porch

于 2013-10-09T19:24:47.150 回答