水平居中
文字的水平居中
text-align:center;
容器的水平居中
div#container {
width:760px;
margin:0 auto;
}
垂直居中
行高與容器高設(shè)為相等
當(dāng)文本行高等于父容器高度時, 就可以實現(xiàn)單行文本垂直居中逸嘀。
<style>
.box {border: 1px solid;
height: 100px;
line-height: 100px; /*行高等于父容器高度*/
}
</style>
</head>
<body>
<div class="box">1233344</div>
</body>
效果如下:
image.png
適用前提 :
- 父容器高度已知
- 居中對象是單行文本
如果有n行文字,可以將行高設(shè)為容器高度的n分之一
父容器設(shè)置上下padding實現(xiàn)垂直居中
<style>
.box {border: 1px solid;
padding: 20px 0; /*父容器上下padding相等 */
}
</style>
</head>
<body>
<div class="box">1334<br/>455</div>
</body>
效果如下:
image.png
適用前提 :
- 父容器高度沒有寫死
display: inline-block 和100%高度的before/after實現(xiàn)垂直居中
<style>
.parent {
border: 5px solid red;
height: 300px;
}
.child {
border: 3px solid blue;
display: inline-block;
vertical-align: middle;
}
.parent:before,.parent:after {
content:'';
border: 2px solid;
height: 100%;
display: inline-block;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">1234444344</div>
</div>
</body>
效果如下:
image.png
適用前提 :
- CSS 的屬性 vertical-align 用來指定行內(nèi)元素(inline)或表格單元格(table-cell)元素的垂直對齊方式碰纬,這個我們后面還會用到萍聊。
table-cell 和 vertical-align: middle實現(xiàn)垂直居中
<style>
.parent {
border: 5px solid red;
height: 100px;
display: table;
}
.child {
border: 3px solid blue;
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">1234444344</div>
</div>
</body>
效果如下:
image.png
利用table本身的特性實現(xiàn)垂直居中
<style>
.parent {
border: 5px solid red;
height: 100px;
}
.child {
border: 2px solid;
}
</style>
</head>
<body>
<table class="parent">
<tr>
<td class="child">table</td>
</tr>
</table>
</body>
效果如下:
image.png
絕對定位和負(fù)margin 實現(xiàn)垂直居中
<style>
.parent {
border: 3px solid red;
height: 100px;
position: relative;
}
.child {
border: 3px solid blue;
position: absolute;
width: 100px;
height: 40px;
top: 50%;
left: 50%;
margin-top: -20px; /*負(fù)margin值為要居中的對象child高度的一半 */
margin-left: -50px; /* 同上 */
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
效果如下:
image.png
適用前提 :
- 需要居中對象寬高已知
絕對定位和translate -50% 結(jié)合使用實現(xiàn)垂直居中
<style>
.parent {
border: 3px solid red;
height: 100px;
position: relative;
}
.child {
border: 3px solid blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">sssddddddddddddddd</div>
</div>
</body>
效果如下:
image.png
適用前提 :
- 這個方法相對于上一種方法來說, 不需要知道居中對象寬高悦析,更為方便寿桨,但是會有兼容性問題
flex 實現(xiàn)居中
<style>
.parent {
border: 3px solid red;
height: 100px;
display: flex;
justify-content: center;/* 主軸方向居中 */
align-items: center; /* 側(cè)軸距中 */
}
.child {
border: 3px solid blue;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">sssddddddddddddddd</div>
</div>
</body>
效果如下:
image.png