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

- 代码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;
后的效果
文字正常显示,背景却被图片挡住了。

- 代码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;
后的效果
下面带有文字的背景没有被上面的内容遮挡

- 代码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;
。后者需要设定宽度

- 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>
网友评论