CSS全面實現內容水平居中,垂直居中
阿新 • • 發佈:2018-11-24
CSS全面實現內容水平居中,垂直居中
概述
本文介紹了各種情況下實現水平居中,垂直居中的方式。
參考連結
水平居中(內容)
行級元素inline/inline-block
.center {
text-align: center;
}
示例程式碼
.wrap {
width: 300px;
height: 200px;
border: 1px solid red;
text-align: center
}
.children {
border: 1px solid black;
/* display: inline-block; */
}
塊級元素(block)
.chlldren {
margin: 0 auto;
}
示例程式碼
.wrap {
width: 300px;
height: 200px;
border: 1px solid red;
}
.children {
margin: 0 auto;
width: 100px;
height: 100px;
border: 1px solid black;
/* display: inline-block; */
}
一行多個塊級元素
使用flex佈局
.wrap {
display: flex;
justify-content: center;
}
.wrap {
display: flex;
justify-content: center;
width: 300px;
height: 200px;
border: 1px solid red;
}
.wrap div{
width: 50px;
height: 50px;
border: 1px solid black;
}
垂直居中(內容)
行級元素(inline)/inline-block
- 單行
- 設定相同的padding
.wrap { padding: 30px 0; }
- 設定相同的line-height和height
.wrap { height: 50px; line-height: 50px; }
- 多行
- flex佈局
.wrap {
display: flex;
align-items: center;
}