可以:before和:after伪元素从父元素继承高度吗?

AKG*_*AKG 19 css inheritance css-selectors pseudo-element

我想知道:before:after伪元素是否可以使用inherit值从父级继承高度,而实际元素是否这样做?

Bol*_*ock 24

否.伪元素可以从其生成元素的父元素继承值的唯一方法是生成元素本身也从其父元素继承.

这是因为从父级到子级的继承发生,一次一级.对于继承在多个级别的后代中工作,每个后代都必须继承.

例如,请考虑以下HTML:

<div class="parent">
    <div class="child">
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

使用以下CSS:

.parent {
    width: 100px;
    height: 100px;
}

.parent > .child:before, .parent > .child:after {
    content: '';
    position: absolute;
    width: inherit;
    height: inherit;
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为即使伪元素具有inherit生成它们的元素的值,也就是说.parent > .child,它不会继承.parent.相反,它们继承了auto两个属性的默认值.

为了使其工作,您还需要.parent > .child继承:

.parent {
    width: 100px;
    height: 100px;
}

.parent > .child {
    width: inherit;
    height: inherit;
}

.parent > .child:before, .parent > .child:after {
    content: '';
    position: absolute;
    width: inherit;
    height: inherit;
}
Run Code Online (Sandbox Code Playgroud)


joe*_*joe 13

我知道这个问题相当陈旧,但我今天偶然发现了它.根据http://www.w3.org/TR/CSS21/generate.html,接受的答案不准确:

:before和:后伪元素继承在文档树中的元素的任何可继承属性到它们所连接.

我只是尝试继承宽度,它工作.

  • 我会编辑我的答案以澄清.我认为它太短了,因此可能会令人困惑. (2认同)