塊級元素垂直格式化的7大屬性:
- margin-top
- border-top
- padding-top
- width
- padding-bottom
- border-bottom
- margin-bottom
這7個屬性只有3個屬性可以設置為auto,即height,margin-top,margin-bottom韧骗。
padding和border都必須設置為特定的值涂佃,或者默認為0(如果沒有設置border-style)截歉。如果設置了border-style夜畴,邊框的寬度會設置為值medium(這個值的定義并不明確)蔑赘。
如果塊元素的margin-top和margin-bottom設置為auto掸茅,它會自動計算為0行疏。
height必須設置為auto或者非負值叼架。
百分數(shù)高度
<div class="outer">
<div class="inner"></div>
</div>
.outer {
width: 200px;
height: 200px;
border: 1px solid red;
margin: 0 auto;
}
.inner {
width: 50%;
height: 50%;
border: 1px solid skyblue;
}
image.png
垂直居中的一種方式是設置margin-top和margin-bottom為(parentHeight-height)/2畔裕。
如果沒有顯式聲明包含塊的height衣撬,百分數(shù)高度會重置為auto。
.outer {
width: 200px;
border: 1px solid red;
margin: 0 auto;
}
.inner {
width: 50%;
height: 50%;
border: 1px solid skyblue;
}
image.png
如果包含塊的高度為auto扮饶,其默認高度是最高塊級子元素的外邊框邊界到其最低塊級子元素外邊框邊界之間的距離淮韭。因此子元素的外邊距會超出包含子元素的塊元素。
auto高度
<div class="outer">
<div class="inner">Hello World</div>
<div class="inner1">HAHA</div>
</div>
.outer {
width: 200px;
height: auto;
background: red;
margin: 0 auto;
}
.inner {
width: 50%;
height: 50%;
margin-top: 25%;
margin-bottom: 25%;
background: skyblue;
}
.inner1 {
background: orange;
margin-bottom: -15px;
}
image.png
不過如果給父級塊元素添加上border-top或者padding-top,則其高度為其最高子元素的上外邊距邊界到其最低子元素的下外邊距邊界之間的距離贴届。
.outer {
width: 200px;
height: auto;
background: red;
margin: 0 auto;
padding-top: 1px; /*或者添加border-top: 1px solid;*/
}
.inner {
width: 50%;
height: 50%;
margin-top: 25%;
margin-bottom: 25%;
background: skyblue;
}
.inner1 {
background: orange;
margin-bottom: -15px;
}
image.png
合并垂直外邊距
下面來看個例子:
<ul class="list">
<li class="cell"></li>
<li class="cell"></li>
<li class="cell"></li>
<li class="cell"></li>
<li class="cell"></li>
</ul>
.list {
list-style: none;
border: 1px solid blue;
counter-reset: li;
width: 400px;
margin: 0 auto;
margin-top: 80px;
}
.cell {
border: 1px solid hotpink;
margin-top: 15px;
margin-bottom: 10px;
}
.cell::after {
counter-increment: li;
content: "Hello World "counter(li);
}
image.png
這邊設置了margin-top為15px靠粪,margin-bottom為10px,但是li之間的距離為15px毫蚓,實際上是margin-top和margin-bottom合并了占键。
負外邊距
如果垂直外邊距都設置為負值,瀏覽器會取兩個外邊距絕對值的最大值元潘。
如果一個為正值畔乙,一個為負值,則從正外邊距減去負外邊距的絕對值翩概。
.list {
list-style: none;
border: 1px solid blue;
counter-reset: li;
width: 400px;
margin: 0 auto;
margin-top: 80px;
}
.cell {
border: 1px solid hotpink;
margin-top: 15px;
margin-bottom: -10px;
}
.cell::after {
counter-increment: li;
content: "Hello World "counter(li);
}
image.png