我刚刚开始学习CSS中的伪元素,例如::before
和::after
。我试图使一个after元素与其父元素具有相同的宽度。例如:
<a href="#">Test</a>
a::before{
content: "";
height: 20px;
width: ?
}
我想将宽度与元素相同。有什么办法吗?
答案 0 :(得分:0)
我认为在使用<div>
之前,您需要先用<a>
包裹<div>
并设置inherit
的宽度。还要在父级中使用position:relative
,在子级中使用position:absolute
:
div::before{
content: "Read this -";
height: 20px;
width:inherit;
position:absolute;
background-color: grey;
right:100%;
}
<div style="background-color: yellow;left: 15em; position:relative; width:15em">
<a href="#" >Read this this this this this</a>
</div>
答案 1 :(得分:0)
您可以通过将a
元素的位置设置为relative
并将伪元素的位置设置为absolute
来实现此目的。
这将使伪元素“继承”其原始元素的宽度,从而允许您设置width: 100%
。
赞:
a{
position: relative;
}
a::after{
content: "";
height: 20px;
width: 100%;
position: absolute;
}
<a href="#">Test</a>