在网页设计中,经常需要在图片上添加文字来丰富页面的内容。在 CSS 中,可以使用伪元素 ::before 和 ::after 来实现这一效果。首先,我们需要在 HTML 代码中添加图片和文本的容器。例...
在网页设计中,经常需要在图片上添加文字来丰富页面的内容。在 CSS 中,可以使用伪元素 ::before 和 ::after 来实现这一效果。
首先,我们需要在 HTML 代码中添加图片和文本的容器。例如:
<div class="image-container">
<img src="image.jpg" alt="My Image">
<p>这是我的图片</p>
</div>
.image-container {
position: relative;
display: inline-block;
}
.image-container::before {
content: attr(data-text); /* 使用data-text属性的值作为伪元素内容 */
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-align: center;
font-size: 1.2em; /* 文字大小 */
font-weight: bold; /* 文字加粗 */
color: white; /* 文字颜色 */
}
.image-container img {
display: block;
width: 100%;
height: auto;
}
.image-container p {
display: none; /* 隐藏原有文字,只保留图片 */
}
<div class="image-container" data-text="这是我的图片">
<img src="image.jpg" alt="My Image">
<p>这是我的图片</p>
</div>
<style>
.image-container {
position: relative;
display: inline-block;
}
.image-container::before {
content: attr(data-text);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-align: center;
font-size: 1.2em;
font-weight: bold;
color: white;
}
.image-container img {
display: block;
width: 100%;
height: auto;
}
.image-container p {
display: none;
}
</style>