In the realm of CSS, inheritance plays a crucial role in defining the styles of child elements based on those of their parent. However, there may be situations where you desire to override this inheritance and customize the styles of child elements independently.
Consider the following HTML structure:
<div>
With this CSS:
form div {font-size: 12px; font-weight: bold;}
Normally, the text blocks "Content of the paragraph" and "Content of the span" would inherit the font size and weight from their parent form.
Manual Style Reversion:
One method to override inheritance involves manually reverting the style changes on the child element:
div {color: green;} form div {color: red;} form div div.content {color: green;}
Adding Multiple Classes:
If you have control over the markup, you can add additional classes to target specific elements:
form div.sub {color: red;} form div div.content {/* Remains green */}
The CSS Working Group is currently exploring the revert property:
div.content { all: revert; }
This property would allow you to explicitly reset all inherited styles on a child element. As of April 2023, most modern browsers (except Safari and Internet Explorer/Edge) support the revert property.
The above is the detailed content of How to Prevent Child Element Inheritance in CSS?. For more information, please follow other related articles on the PHP Chinese website!