Home >Web Front-end >CSS Tutorial >How to Prevent CSS Inheritance from Parent Elements?
CSS Inheritance and Overriding
In certain circumstances, it may be necessary to prevent a child element from inheriting styles inherited from its parent element. While there is no specific CSS property to achieve this, it is possible to manually revert style changes or add additional classes to define more specific styling.
For example, consider the following HTML and CSS:
HTML:
<body> <div>
CSS:
form div {font-size: 12px; font-weight: bold;} div.content { /* Can anything go here? */ }
Under normal circumstances, the text blocks "Content of the paragraph" and "Content of the span" would inherit the font size and weight from the parent "form div" element, resulting in both texts being bold and 12px.
To prevent this inheritance and limit the styling to just "Content of the paragraph," one can manually revert style changes:
div { color: green; } form div { color: red; } form div div.content { color: green; }
Alternatively, if possible, adding additional classes to the markup can provide more precise styling:
<form div.sub { color: red; } form div div.content { /* remains green */ }
Recent versions of modern browsers now support the "revert" property to explicitly revert inheritance on specific elements:
div.content { all: revert; }
This allows for more concise and flexible styling overrides.
The above is the detailed content of How to Prevent CSS Inheritance from Parent Elements?. For more information, please follow other related articles on the PHP Chinese website!