简体   繁体   中英

How to make a div and its children to ignore its parent styles?

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?

you could use :not

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

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

Browser support : https://developer.mozilla.org/en-US/docs/Web/CSS/:not

It's a matter of which selector is in effect for the chosen styling rule.

  1. Selectors which come later in the styling order overrule the ones that come before
  2. Selectors with a higher specificity overrule the ones with lower specificity even if the latter come after the former

So make this selector.
. house .room.porch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM