美文网首页
margin-top为负数,img图片遮挡div背景的问题

margin-top为负数,img图片遮挡div背景的问题

作者: CoderZb | 来源:发表于2022-12-06 17:03 被阅读0次

如下图所示,相对于container来说,图片在上,带有背景的文字在下,这两个内容是同级的。
当未设置margin-top(或者margin-top为正数)时,界面的显示看不出有什么异常。
当设置margin-top为负数时,会出现上面的图片遮挡下面的div背景的问题。
但是当把图片换成div就没有这种问题。看来图片和margin-top为负数同时存在 且 margin-top是相对于图片的距离的时候,会出现页面显示的问题

1、默认效果

image.png
  • 代码1
<div class="container">
     <div class="img_box">
         <img src="./aa.jpeg">
     </div>
    <div class="text_box">测试文字</div>
</div>
<style>
.container {
    color: white;
    text-align: center;
    width: 200px;
    margin:100px auto;
}
.img_box img {
    width:200px;
    height: 200px;
}
.text_box {
    height: 160px;
    background:red;
}

2.1、对text_box设置margin-top:-60px;后的效果

文字正常显示,背景却被图片挡住了。

image.png
  • 代码2.1
<div class="container">
     <div class="img_box">
         <img src="./aa.jpeg">
     </div>
    <div class="text_box">测试文字</div>
</div>
<style>
.container {
    color: white;
    text-align: center;
    width: 200px;
    margin:100px auto;
}
.img_box img {
    width:200px;
    height: 200px;
}
.text_box {
    height: 160px;
    background:red;
    margin-top:-60px;
}

2.2 将图片换成div,然后对text_box设置margin-top:-60px;后的效果

下面带有文字的背景没有被上面的内容遮挡

image.png
  • 代码2.2
<div class="container">
     <div class="img_box">
         <div style='width:200px;height:200px;color: orange;background:blue;'>上面的文字</div>
     </div>
    <div class="text_box">测试文字</div>
</div>
<style>
.container {
    color: white;
    text-align: center;
    width: 200px;
    margin:100px auto;
}
.img_box img {
    width:200px;
    height: 200px;
}
.text_box {
    height: 160px;
    background:red;
    margin-top:-60px;
}

</style>

3、解决办法:

text_box设置position:relative;或者display:inline-block;。后者需要设定宽度

image.png
  • css
<div class="container">
     <div class="img_box">
         <img src="./aa.jpeg">
     </div>
    <div class="text_box">测试文字</div>
</div>
<style>
.container {
    color: white;
    text-align: center;
    width: 200px;
    margin:100px auto;
}
.img_box img {
    width:200px;
    height: 200px;
}
.text_box {
    height: 160px;
    background:red;
    margin-top:-60px;
    position: relative;
    /*width: 100%;
    display:inline-block;*/
}

</style>

深入理解CSS中的层叠上下文和层叠顺序

相关文章

网友评论

      本文标题:margin-top为负数,img图片遮挡div背景的问题

      本文链接:https://www.haomeiwen.com/subject/errifdtx.html