Home > Web Front-end > CSS Tutorial > How can I isolate a div from public CSS styles in HTML?

How can I isolate a div from public CSS styles in HTML?

Patricia Arquette
Release: 2024-10-26 14:44:02
Original
212 people have browsed it

How can I isolate a div from public CSS styles in HTML?

Isolating a div from Public CSS Styles

In HTML, CSS cascading and inheritance can sometimes affect elements within a div that are not intended to be styled by the public CSS rules. This can result in unexpected formatting issues. To address this, CSS Cascading and Inheritance Level 3 introduced the all shorthand property and the unset keyword.

Using the all and unset Keywords

To prevent tags inside a div from being affected by public styles, you can set all: initial on the div and all: unset on its descendants. This will block inheritance for all properties on the div and allow inheritance within the div itself.

Example

Consider the following HTML:

<code class="html"><div id='mydiv'>
  <img src='an image source' />
  <h1>Hi it's test</h1>
</div></code>
Copy after login

And the following CSS:

<code class="css">img {
  width:100px;
  height:100px;
}
h1 {
  font-size:26px;
  color:red;
}</code>
Copy after login

Without isolating the div, the image and heading inside the div would inherit the public styles. To isolate it, apply the following CSS:

<code class="css">#mydiv {
  all: initial;
}
#mydiv * {
  all: unset;
}</code>
Copy after login

This will block any public styles from affecting the elements within the #mydiv div while allowing them to inherit styles defined within the div itself.

Cross-Browser Support

The all property is supported in most modern browsers. For older browsers, you can manually specify initial for all CSS properties to achieve similar results. However, note that this method is less effective than using the all property.

The above is the detailed content of How can I isolate a div from public CSS styles in HTML?. 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