當時說到了盒模型,盒模型包含着margin,爲何要在這裏說margin呢?由於元素和元素在垂直方向上margin裏面有坑。css
咱們來看一個例子:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>margin塌陷</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
.father{
overflow:hidden;
width:300px;
border:1px solid gray;
}
.box1{
width:200px;
height:50px;
background-color:red;
margin-bottom:20px;
float:left
}
.box2{
margin-top:50px;
width:400px;
height:150px;
background-color:green;
float:left
}
span{
background-color:red;
}
span.a{
margin-right:20px;
}
span.b{
margin-left:20px;
}
</style>
</head>
<body>
<div class="father">
<div class="box1"></div>
<div class="box2"></div>
</div>
<span class="a">內容</span>
<span class="b">內容</span>
</body>
</html>
當給兩個標準流下兄弟盒子 設置垂直方向上的margin時,那麼以較大的爲準,那麼咱們稱這種現象叫塌陷。咱們稱爲這種技巧叫「奇淫技巧」。記住這種現象,在佈局垂直方向盒子的時候主要margin的用法。佈局
當咱們給兩個標準流下的兄弟盒子設置浮動以後,就不會出現margin塌陷的問題。spa
div{ width: 780px; height: 50px; background-color: red; /*水平居中盒子*/ margin: 0px auto; /*水平居中文字*/ text-align: center; }
當一個div元素設置margin:0 auto;時就會居中盒子,那咱們知道margin:0 auto;表示上下外邊距離爲0,左右爲auto的距離,那麼auto是什麼意思呢?code
設置margin-left:auto;咱們發現盒子儘量大的右邊有很大的距離,沒有什麼意義。當設置margin-right:auto;咱們發現盒子儘量大的左邊有很大的距離。當兩條語句並存的時候,咱們發現盒子儘量大的左右兩邊有很大的距離。此時咱們就發現盒子居中了。htm
另外如何給盒子設置浮動,那麼margin:0 auto失效。blog
使用margin:0 auto;注意點:it
1.使用margin: 0 auto;水平居中盒子必須有width,要有明確width,文字水平居中使用text-align: center;io
2.只有標準流下的盒子 才能使用margin:0 auto;class
當一個盒子浮動了,固定定位,絕對定位(後面會講),margin:0 auto; 不能用了
3.margin:0 auto;居中盒子。而不是居中文本,文字水平居中使用text-align: center;
另外你們必定要知道margin屬性是描述兄弟盒子的關係,而padding描述的是父子盒子的關係
若是讓你們實現如圖的效果,應該有很多的同窗作不出來。
那麼咱們來看看這個案例,它的坑在哪裏?
下面這個代碼應該是你們都會去寫的代碼。
*{ padding: 0; margin: 0; } .father{ width: 300px; height: 300px; background-color: blue; } .xiongda{ width: 100px; height: 100px; background-color: orange; margin-top: 30px; }
由於父親沒有border,那麼兒子margin-top實際上踹的是「流」 踹的是行,因此父親掉下來了,一旦給父親一個border發現就行了。
那麼問題來了,咱們不可能在頁面中平白無故的去給盒子加一個border,因此此時的解決方案只有一種。就是使用父親的padding。讓子盒子擠下來。