我正在尝试在img之上制作一个白色div。
我尝试过绝对和相对位置,但没有成功。我被卡住了。
该框显示在 img 容器下方。
我做错了什么?:)
.img_container {
margin-left: 40px;
margin-right: 40px;
background-size: cover;
background-position: center center;
position: relative;
text-align: center;
}
.img_container .the_img img {
width: 100%;
height: 420px;
}
.img_container .the_img .container_white{
width: 900px;
height: 50px;
margin: 0 auto;
background: white;
position:absolute;
}
<div class="img_container">
<div class="the_img">
<?php echo get_the_post_thumbnail( get_the_ID(), 'large'); ?>
<div class="container_white">¨
</div>
</div>
</div>
<div class="fixfloat"></div>
get_the_post_thumbnail
唯一要做的就是在代码中插入图像元素。 例如,它将生成如下内容:
<img width="" height="" src="" class="" alt="" large="" srcset="" sizes="">
当然填充了您的自定义值。 为了更好地演示,我用返回的img
标签替换了 php 函数调用。
如果要相对于其父级放置div:
- 您的父母应该
position: relative
- 你的孩子应该
postion: absolute
在您的情况下,the_img
元素是父元素。 子项、img
和container_white
都必须是绝对的,才能将它们从正常的文档流中删除。请参阅截取的代码。
.img_container {
margin-left: 40px;
margin-right: 40px;
background-size: cover;
background-position: center center;
position: relative;
/**text-align: center;**/
}
.img_container .the_img img {
width: 100%;
height: 420px;
position: absolute;
}
.img_container .the_img .container_white{
width: 900px;
height: 50px;
margin: 0 auto;
background: white;
position:absolute;
}
.the_img{
position: relative;
}
<div class="img_container">
<div class="the_img">
<img src="https://images.pexels.com/photos/386148/pexels-photo-386148.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="beach">
<div class="container_white"></div>
</div>
</div>
<div class="fixfloat"></div>
所以你唯一要做的就是
- 使
the_img
成为relative
- 使
img
absolute
注意:我从img_container
中删除了text-align: center
,只是为了更好地显示。