Home > Web Front-end > CSS Tutorial > How to Prevent CSS Inheritance from Parent Elements?

How to Prevent CSS Inheritance from Parent Elements?

Barbara Streisand
Release: 2024-11-26 06:47:12
Original
605 people have browsed it

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>
Copy after login

CSS:

form div {font-size: 12px; font-weight: bold;}
div.content
{
 /* Can anything go here? */
}
Copy after login

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; }
Copy after login

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 */ }
Copy after login

Recent versions of modern browsers now support the "revert" property to explicitly revert inheritance on specific elements:

div.content {
  all: revert;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template