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>
And the following CSS:
<code class="css">img { width:100px; height:100px; } h1 { font-size:26px; color:red; }</code>
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>
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!