CSS Cascading and Inheritance Level 3推出了
the all shorthand property和
the unset keyword,它们可以一起实现这一点。
For example, if an author specifies all: initial on an element it will
block all inheritance and reset all properties, as if no rules
appeared in the author, user, or user-agent levels of the cascade.
This can be useful for the root element of a “widget” included in a
page, which does not wish to inherit the styles of the outer page.
Note, however, that any “default” style applied to that element (such
as, e.g. display: block from the UA style sheet on block elements such
as
您将需要应用所有:初始到您的div和所有:未设置到其后代:
#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;
}
或者,对于更广泛的浏览器支持,您可以手动尝试通过设置所有已知的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;
...
}
您可以鼓励浏览器支持所有速记属性,并通过以下问题链接跟踪其采用情况:
here提供了所有速记属性的最新浏览器支持信息。