gpt4 book ai didi

html - 如何从公共(public) CSS 样式中分离出一个 div?

转载 作者:技术小花猫 更新时间:2023-10-29 11:34:36 24 4
gpt4 key购买 nike

我有一些代码,例如这里的 html

<html>
<body>
<img src='an image source'/>
<h1>Hi it's test</h1>
<div id='mydiv'>
<img src='an image source'/>
<h1>Hi it's test</h1>
</div>
</body>
</html>

如果我使用以下 CSS 代码来设置样式:

img{
width:100px;
height:100px;
}
h1{
font-size:26px;
color:red;
}

问题是:如何防止和隔离 mydiv div 标签内的标签,使其不受公共(public)标签样式的影响?

最佳答案

CSS Cascading and Inheritance Level 3介绍 the all shorthand propertythe unset keyword ,它们共同使您可以方便地实现这一目标。

For example, if an author specifies all: initial on an element it willblock all inheritance and reset all properties, as if no rulesappeared in the author, user, or user-agent levels of the cascade.

This can be useful for the root element of a "widget" included in apage, which does not wish to inherit the styles of the outer page.Note, however, that any "default" style applied to that element (suchas, e.g. display: block from the UA style sheet on block elements suchas <div>) will also be blown away.

您需要申请 all: initial到你的 div 和 all: unset对其后代:

#mydiv {
all: initial; /* blocking inheritance for all properties */
}
#mydiv * {
all: unset; /* allowing inheritance within #mydiv */
}

您可能希望在您的 div 上使用类而不是 id,这样您编写的任何为其后代设置样式的规则就不必匹配或超过此规则中使用的高特异性。

为了真正安全,您可能还想阻止潜在伪元素后代的样式:

#mydiv::before,
#mydiv::after,
#mydiv *::before,
#mydiv *::after {
all: unset;
}

或者,为了获得更广泛的浏览器支持,您可以手动尝试执行 all 的操作通过设置所有已知的 CSS 属性来实现(不要忘记前缀版本):

#mydiv {
/*
* using initial for all properties
* to totally block inheritance
*/
align-content: initial;
align-items: initial;
align-self: initial;
alignment-baseline: initial;
animation: initial;
backface-visibility: initial;
background: initial;
...
}

#mydiv::before,
#mydiv::after,
#mydiv *,
#mydiv *::before,
#mydiv *::after {
/*
* using inherit for normally heritable properties,
* and initial for the others, as unset does
*/
align-content: initial;
align-items: initial;
align-self: initial;
...
color: inherit;
...
}

您可以鼓励浏览器支持 all速记属性并通过这些问题链接跟踪其采用情况:

all 的最新浏览器支持信息速记属性可用here .

关于html - 如何从公共(public) CSS 样式中分离出一个 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10064172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com