在使用before
伪类时,背景色不会起作用的常见原因是没有给before
伪元素设置足够的宽度和高度。下面是一个解决这个问题的示例代码:
HTML代码:
这是一个段落
CSS代码:
.container {
position: relative;
}
.container p:before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: red;
opacity: 0.5;
z-index: -1;
}
在上面的示例中,我们将容器元素 .container
设置为相对定位,并在其子元素 p
上使用 before
伪类来创建一个背景。为了让背景生效,我们给 before
伪元素设置了宽度为100%和高度为100%,以确保它覆盖整个父元素。
通过设置 position: absolute;
、top: 0;
、left: 0;
,我们将 before
伪元素定位到父元素 .container
的左上角。
最后,我们给 before
伪元素设置了 background-color
属性来定义背景色,并通过 opacity
属性来调整背景的透明度。
使用以上代码,你将能够在 before
伪元素中成功应用背景色。