Can the :before and :after pseudo-elements inherit height from the parent element?

我只是一个虾纸丫 提交于 2019-12-18 14:12:51

问题


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?


回答1:


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.

As an example, consider the following HTML:

<div class="parent">
    <div class="child">
    </div>
</div>

With the following CSS:

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

.parent > .child:before, .parent > .child:after {
    content: '';
    position: absolute;
    width: inherit;
    height: inherit;
}

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.

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;
}



回答2:


I know this question is fairly old, but I stumbled on it today. According to http://www.w3.org/TR/CSS21/generate.html, the accepted answer isn't accurate:

The :before and :after pseudo-elements inherit any inheritable properties from the element in the document tree to which they are attached.

I just tried inheriting width and it worked.




回答3:


Concerning these answers, I was just bumping into the aspect of transformation. It may resemble on inheritance; I hope it helps somebody.

Having this:

<div class="box">    
  <div class="frame"></div>
</div>

and this transformation for frame:

transform: rotate(10deg);

Then the frame:before and frame:after are also transformed. Yet they do not have the properties of frame, such as width and height, which is like explained above. Full example see here:

http://jsfiddle.net/chafpgwt/1/

On this fiddle, there are three nested squares, each rotated by 10 deg, but the transform definition is only set for the frame, not for frame:after neither frame:before.

It is a pitfall to think transformations also are not "inherited", as everything else is neither. The transformation has influence in another context.



来源:https://stackoverflow.com/questions/12124953/can-the-before-and-after-pseudo-elements-inherit-height-from-the-parent-elemen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!