答案 0 :(得分:4)
在img
中换取div
并向psuedoelement
添加div
。
使用pseudoelement
表示您无需声明img
容器的高度和宽度。
div {
position: relative;
display: inline-block;
}
img {
vertical-align: bottom;
}
div:after {
content: '';
position: absolute;
left: 3rem;
top: 3rem;
border: 2px solid black;
width: 100%;
height: 100%;
z-index: -1;
}
<div><img src="https://unsplash.it/400"></div>
更完整的布局示例......
section {
padding: 3rem 4.5rem;
}
figure {
position: relative;
float: left;
margin: 0 3rem 1rem 0;
}
img {
vertical-align: bottom;
}
figure:after {
content: '';
position: absolute;
left: 1.5rem;
bottom: 1.5rem;
border: 2px solid black;
width: 100%;
height: 100%;
z-index: -1;
}
h3 {
margin-top: 0;
}
<section>
<figure><img src="https://unsplash.it/260"></figure>
<h3>A Title</h3>
<h5>Subtitle subtitle subtitle subtitle</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
答案 1 :(得分:2)
这是一个非常基本的示例,说明如何使用css在图像下添加矩形。 检查代码段。
div {
position: absolute;
width: 350px;
height: 230px;
border: 2px solid grey;
top: 30px;
left: 30px;
z-index: -10;
}
img {
width: 350px;
}
&#13;
<img src="https://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-23.jpg" />
<div></div>
&#13;
答案 2 :(得分:1)
执行此操作的一种方法是为边框使用单独的div
:将position: absolute;
设置为图像,将边框设置为div,然后使用z-index
放置图像在边界div之上。
你必须使用容器div来拥抱图像和边框div。此容器获取position: relative
(将子元素的position: absolute
设置为生效)并且需要具有整个子元素集的维度。
.container {
position: relative;
width: 240px;
height: 120px;
}
.container div {
width: 200px;
height: 100px;
}
.image {
z-index: 20;
position: absolute;
top: 0px;
background-color: lightblue;
}
.rect {
z-index: 10;
position: absolute;
top: 20px;
left: 40px;
border: 1px solid #666;
}
&#13;
<p>Text</p>
<p>Text</p>
<div class="container">
<div class="image">
Image
</div>
<div class="rect">
</div>
</div>
<p>Text</p>
<p>Text</p>
&#13;