如何使psudo元素与其元素的宽度相同

时间:2019-12-13 01:42:01

标签: html css

我刚刚开始学习CSS中的伪元素,例如::before::after。我试图使一个after元素与其父元素具有相同的宽度。例如:

<a href="#">Test</a>
a::before{
content: "";
height: 20px;
width: ?
}

我想将宽度与元素相同。有什么办法吗?

2 个答案:

答案 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>