【发布时间】:2023-03-12 05:50:02
【问题描述】:
我想在图像上悬停时添加背景颜色叠加效果。但是我用css pseudo-class:after尝试了几次,它只是不起作用,代码为:
<div class="test">
<img src="assets/img/slide1.jpeg" class="overlay" alt="">
<!-- my image tag -->
</div>
css:
.test{
width: 50%;
height: 50%;
}
.overlay{
width: 100%;
height: 100%;
position: relative;
}
.overlay:after{
content: "test";
position: absolute;
font-size:3em;
}
.overlay:aftercontent 没有显示,但是当我在 <p> 或 <span>tag 上使用 :after 类时它正在工作,并且我打算在我的 <img> 上添加叠加颜色效果标记为:
/*adding background color on the image tag using :after*/
.overlay:after{
content: " ";
position: absolute;
width: 100%;
height: 100%;
background-color: red;
z-index: 0;
}
所以我的问题是:
1、为什么伪类:after对img标签不起作用,而对<p>或<h1>等文本标签起作用?
2. 我的代码使用:after添加红色背景颜色有什么问题吗?
【问题讨论】:
-
:after 仅适用于可以包含文本内容的容器元素(因为它通过在初始内容之后附加内容来工作),所以正如您所发现的,不幸的是它不适用于 img,您需要使用包装元素并将其附加到该元素上。
标签: css