可以:before和:after伪元素从父元素继承高度吗? [英] Can the :before and :after pseudo-elements inherit height from the parent element?
问题描述
我想知道:之前
和:之后
伪元素是否可以继承父元素 inherit
值,没有实际的元素这样做?
I am wondering whether the :before
and :after
pseudo-elements can inherit the height from parent using the inherit
value, without the actual element doing so?
推荐答案
伪元素可以从其生成元素的父代继承值的唯一方法是生成元素本身也从其父代继承。
No. The only way that pseudo-elements can inherit values from the parent of their generating element is when the generating element itself is also inheriting from its parent.
这是因为继承发生从父母到孩子,一次一个水平。
This is because inheritance occurs from a parent to a child, one level at a time. For inheritance to work across several levels of descendants, every descendant must inherit.
例如,考虑下面的HTML:
As an example, consider the following HTML:
<div class="parent">
<div class="child">
</div>
</div>
使用以下CSS:
.parent {
width: 100px;
height: 100px;
}
.parent > .child:before, .parent > .child:after {
content: '';
position: absolute;
width: inherit;
height: inherit;
}
这不会工作,因为即使伪元素的值为 inherit
,生成它们的元素,即 .parent> .child
,不会继承 .parent
。相反,他们继承两个属性的默认值 auto
。
This will not work because even though the pseudo-elements have values of inherit
, the element generating them, that is, .parent > .child
, does not inherit from .parent
. Instead, they inherit the default value of auto
for both properties.
为了这个工作,你将需要拥有 .parent> .child
继承:
In order for this to work you will need to have .parent > .child
inherit as well:
.parent {
width: 100px;
height: 100px;
}
.parent > .child {
width: inherit;
height: inherit;
}
.parent > .child:before, .parent > .child:after {
content: '';
position: absolute;
width: inherit;
height: inherit;
}
这篇关于可以:before和:after伪元素从父元素继承高度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!