The CSS selector has a weight. When the style settings of different separators conflict, the style set by the selector with a higher weight will be used.
If the CSS selector has the same weight, the style follows the proximity principle. The final definition of the selector adopts the style of the selector.
If you ignore the CSS selector weight, it will cause unexpected minor problems.
Requirements and Solutions
CSS selection operator weight is very important
Now we need to set the word "important" to Red. Our practice is as follows:
Solution 1: Use the sub-Selector
CSS selection operator weight is very important
Solution 2: Create a class
CSS selection operator weight is very important
Many engineers recommend solution 1, because using a sub-selector can avoid adding classes, making HTML code more concise. It makes sense to consider this, but in this case, you need to add new text.
Change demand
The CSS selector weight is very important, so we should be careful with it.
We need to set 'careful Process' to green, which we may do.
Very important. We need to handle it with caution.
In this case, the 'careful process' is set to green, but the # test span with a higher weight is set to red. The child selector inadvertently affects the newly added code. To meet our expectations, rewrite the Code as follows:
Very important. We need to handle it with caution.
What happens if solution 2 is used?
The CSS selector weight is very important, so we should be careful with it.
Because there is no sub-selector, We can mount the new class for the newly added code to complete style settings smoothly.
Summary
When a sub-selector is used, the weight of the CSS selector is increased. The higher the weight of the CSS selector, the less likely the style to be overwritten, and the more likely it will affect other selector. Therefore, unless it is determined that the HTML structure is very stable and will not be modified, do not use the child selector whenever possible. To ensure that the style is easily overwritten and maintainability is improved, the CSS selector must ensure that the weight is as low as possible.
Low weight principle -- avoid abuse of sub-selectors