水平居中:
根據子元素為行內元素還是塊狀元素,寬度一定還是寬度未定的變化,采取的布局方案不同。
- 子元素是行內元素
HTML:
<div class="father">
<span class="child-inline">行內元素水平居中</span>
</div>
CSS:
.father{
width: 100%;
height: 100px;
text-align: center;
background: #666;
}
- 子元素是無寬度塊級元素
HTML:
<div class="father">
<div class="child-noWidth">我是不定寬的塊級元素</div>
</div>
CSS:
.father{
text-align: center;
}
.father .child-noWidth{
display: inline;
}
- 子元素是有寬度的塊級元素
HTML:
<div class="father">
<div class="child-width">定寬塊級元素水平居中</div>
</div>
CSS:
.child-width{
width: 200px;
margin:0 auto;
}
- 對以上情況都通用的方法:flex布局(可愛的自適應布局)
HTML:
<div class="father">
<div class="child ">我是子元素</div>
</div>
CSS:
.father{
display: flex;
justify-content: center;
background: lightblue;
margin-top: 20px;
}
垂直居中:
分為多行內聯文本,單行內聯文本以及塊級元素。
- 單行內聯文本(保證行高與元素高度一致)
HTML:
<div class="container">
<span>我是只有一行的小文本</span>
</div>
CSS:
.container{
height: 30px;
line-height: 30px;
}
- 多行內聯文本
HTML:
<div class="container">
<span>我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本我是有多行的大文本</span>
</div>
CSS:
.container{
width: 100%;
height: 200px;
background: lightblue;
display: table-cell;
vertical-align: middle;
}
3.塊級元素(借助position)
HTML:
<div class="f">
<div class="c">hello</div>
</div>
CSS:
.f{
position: relative;
width: 100%;
height:200px;
background: lightblue;
}
.c{
position: absolute;
width: 100%;
height: 100px;
top: -50px;
margin-top: 100px;
background: lightpink;
}
先以父元素高度的一半作為margin-top的值,再將top設置為負的自身高度的一半,即可對準父元素的中心基準線
- 對以上情況都通用的方法: flex布局(可愛的自適應布局)
HTML:
<div class="father">
<div class="child">hello,this is child-element</div>
</div>
<div class="father">
<span class="child">hello,this is child-element</span>
</div>
CSS:
.father
{
margin-top: 10px;
height: 50px;
width: 100%;
/*通用的垂直居中*/
display: flex;
align-items:center;
background: lightblue;
}
.child
{
background: lightpink;
}