【css】使用margin时易出现的错误

前言:margin在布局的时候还是蛮常用到,不过margin还是容易产生一些问题的。

一、margin-top传递给了父级。

<body>
<style>
body { margin:0; background:pink; }
.box1 { width:200px; height:200px; background:#333;}
.box2 { width:100px; height:100px; margin-top:100px; margin-left:100px; background:#666;}
</style>
<div class="box1">
	<div class="box2">
    
    </div>
</div>
</body>

想要实现的效果:想要让box2在box1里面,距离box1上边为100px; 距离左边为100px;

实际运行的效果:


这时候发现,box2在box1里面确实是距离左边是100px的, 奇怪的是,box2在box1里面距离上边的为0px,而且box1距离body的距离为100px;了。这就是box2把margin-top值,传递给了父级。

解决方法①:给父级添加border边框

<body>
<style>
body { margin:0; background:pink; }
.box1 { width:200px; height:200px; background:#333; border:1px solid #000;}
.box2 { width:100px; height:100px; margin-top:100px; margin-left:100px; background:#666;}
</style>
<div class="box1">
	<div class="box2">
    
    </div>
</div>
</body>
解决方法②:给父级添加overflow:hidden;
<body>
<style>
body { margin:0; background:pink; }
.box1 { width:200px; height:200px; background:#333; overflow:hidden;}
.box2 { width:100px; height:100px; margin-top:100px; margin-left:100px; background:#666;}
</style>
<div class="box1">
	<div class="box2">
    
    </div>
</div>
</body>

这两个方法都很好的解决了这问题。

二、上下方向margin重叠问题。

<body>
<style>
body { margin:0; background:pink; }
div { float:left;  }
.box1 { width:100px; height:100px; background:#333; margin-right:100px; }
.box2 { width:100px; height:100px; background:#666; margin-left:120px;   }
</style>
<div class="box1"></div>
<div class="box2"></div>
</body>


box1跟box2的距离为220px;说明两者间的距离为两者maigin值的相加;这并没有问题,而问题是出现在margin-top跟margin-bottom;

margin-topmaigin-bottom的问题。

<body>
<style>
body { margin:0; background:pink; }
.box1 { width:100px; height:100px; background:#333; margin-bottom:100px; }
.box2 { width:100px; height:100px; background:#666; margin-top:120px;   }
</style>
<div class="box1"></div>
<div class="box2"></div>
</body>

运行代码发现

box1跟box2的距离不是220px; 也不是100px; 最终是120px。相反反向的margin会重叠,距离的值取决于大的值。这要特别注意跟margin-left、margin-right的区别了。


猜你喜欢

转载自blog.csdn.net/w390058785/article/details/80461324