CSS的边距(2)
边距(有浮动的情况)
块级元素
.box1
{
background-color:tan;
margin: 50px;
float: left;
/*
当元素浮动时
1.块级元素水平方向上的外边距叠加
2.块级元素垂直方向上的外边距叠加
3.子元素的top不再向父级元素传递
*/
}
行级元素
a{
background-color: red;
margin: 30px;
float: left;
/*
当有浮动时
上下外边距对行级元素起作用
*/
}
示例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>边距</title>
</head>
<style type="text/css">
.box1,.box2{
width:200px;
height:200px;
}
.box1_1,.box2_1{
width:100px;
height:100px;
/*margin: 100px;*/
margin-top: 10px;
margin-left: 100px;
}
.box1{
background-color:tan;
margin: 50px;
float: left;
/*当元素浮动时
1.块级元素水平方向上的外边距叠加
2.块级元素垂直方向上的外边距叠加
3.子元素的top不在向父级元素传递*/
}
.box1_1{
background-color:deeppink;
/* margin: 100px;*/
}
a{
background-color: red;
/*当有浮动时
上下外边距对行级元素起作用*/
margin: 30px;
float: left;
}
.box2{
background-color:thistle;
margin: 50px;
float: left;
}
.box2_1{
background-color:pink;
}
</style>
<body>
<div class="box1">
<div class="box1_1">box1_1</div>
<a>a1</a>
<a>a2</a>
</div>
<div class="box2">
<div class="box2_1">box2_1</div>
</div>
</body>
</html>
效果展示
解释
1.box1和box2的水平距离为100px,是box1和box2的左右外边距叠加造成的。
2.a1、a2和box1-1的距离为30px,是有了浮动的前提,上下外边距对行级元素起作用造成的。