水平居中
1.內(nèi)聯(lián)元素(如span伶椿、img再芋、button菊霜、a標(biāo)簽等)使用text-align: center;
.parent{
text-align: center;
}
2.父元素中誰需要居中,就給其設(shè)置margin: 0 auto;
使盒子自己居中
.child{
width: 200px;
height: 200px;
border: 1px solid red;
margin: 0 auto;
}
3.使用定位屬性
.parent{
position: relative;
}
.child{
width: 200px;
height: 200px;
border: 1px solid red;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
4.使用flex
.parent{
display: flex;
justify-content: center;
}
.child{
width: 200px;
height: 200px;
border: 1px solid red;
}
水平垂直居中
1.使用flex
.parent{
height: 600px;
border: 1px solid green;
display: flex;
justify-content: center;
align-items: center;
}
.child{
width: 200px;
height: 200px;
border: 1px solid red;
}
2.使用定位屬性(爸爸relative济赎,兒子absolute)
.parent{
height: 600px;
border: 1px solid green;
position: relative;
}
.child{
width: 200px;
height: 200px;
border: 1px solid red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
3.使用margin: auto;
.parent{
height: 600px;
border: 1px solid green;
position: relative;
}
.child{
width: 200px;
height: 200px;
border: 1px solid red;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
垂直居中
4.使用table自帶的功能
.parent{
border: 1px solid red;
height: 600px;
}
.child{
border: 1px solid green;
}
<table class="parent">
<tr>
<td class="child">
一串文字一串文字一串文字一串文字一串文字
</td>
</tr>
</table>
5.div裝成table
<div class="table">
<div class="tr">
<div class="td">一串文字一串文字一串文字一串文字一串文字
</div>
</div>
</div>
<style>
div.table{
display: table;
border: 1px solid red;
height: 600px;
}
div.tr{
display: table-cell;
border: 1px solid blue;
vertical-align: middle;
}
.td{
border: 1px solid black;
}
</style>