1. Refine the selector

Make the selector description more precise by using Combinator (see CSS selector -mDN). For example, for the following code snippet, if you want to style.apple in.cellphones, just use.apple, It’s going to affect the dot apple in dot fruit.

<div class="cellphones">
  <div class="apple"></div>
</div>
<div class="fruit">
  <div class="apple"></div>
</div>
Copy the code

A more accurate description can be Descendant Combinator or Child Combinator. The more accurate the description is, the higher the priority is. The higher-priority description overrides the lower-priority description.

/* Descendant combinator: all descendant nodes */
.cellphones .apple {
	border: 1px solid black;
}

/* More accurate descendant combinator */
body .cellphones .apple {
  border: 1px solid blue;
}

/* Child combinator: direct child node */
.cellphones > .apple {
  border: 1px solid red;
}
Copy the code

If you add all of the above styles to.apple in sequence, you end up with a blue border.

For details about priority rules, see CSS Priority

2. Write the selector name again

It’s essentially a special case of the previous case. For.apple, add the following style:

.cellphones > .apple.apple {
  border: 1px solid purple;
}
.cellphones > .apple {
  border: 1px solid red;
}
Copy the code

Finally, the border will be purple.

3. Change the order in the CSS stylesheet

For styles specified by the same type selector, the styles later in the CSS file override the previous styles. For example, for div elements in the following code, the browser renders them in red:

<div class="redBorder" class="blackBorder"></div>
Copy the code
.blackBorder {
  border: 1px solid black;
}
.redBorder {
  border: 1px solid red;
}
Copy the code

Note that although.blackborder appears after.redborder in the HTML file, the priority is determined by the order in which they appear in the CSS file. That is, the.redborder that is further down in the CSS file will be adopted.

4. Proactively Prioritize (not recommended)

Another simple but not recommended approach is to add keywords to the style you want to use! Important makes style priority extremely high. Such as:

<div class="redBorder" class="greenBorder"></div>
Copy the code
.greenBorder {
  border: 1px solid green ! important;
}
.redBorder {
  border: 1px solid red;
}
Copy the code

For the above code, the border will appear green.

Use! Important is a very bad habit that breaks the cascading rules inherent in stylesheets and makes debugging very difficult!

Reference: Priority – MDN CSS style conflict how to resolve – Magic time machine