前端在項目開發(fā)過程會遇到很多的水平和垂直居中,沒辦法,美觀。以前我的做法基本都是按套路來,文字水平居中用text-align:center 垂直居中就用line-height: 【容器高度】,如果多行文字的話就用內聯(lián)元素包起來,然后再用line-height, 圖片的話一般會搭配display: table;verticle-align:middle來使用。最近遇到一個強大的屬性來應對一切垂直水平居中來分大家分享一下,下面直接上:
1 文字
1,設置父元素: display: flex
2,垂直居中: align-items: center
<style>
.container{
width: 200px;
height: 200px;
display: flex;
background: #f5f5f5;
align-items: center;
}
</style>
<body>
<div class="container">
今天天氣很好,心情也很好!
</div>
</body>

image.png
3,水平居中: justify-content: center,為方便看效果我把寬度加到400px, 下面看下代碼及效果
<style>
.container{
width: 400px;
height: 200px;
display: flex;
background: #f5f5f5;
justify-content: center;
}
</style>
<body>
<div class="container">
今天天氣很好,心情也很好!
</div>
</body>

image.png
2 下面試試圖片
為了快速看效果,這次直接加上兩個屬性
<style>
.container{
width: 400px;
height: 400px;
display: flex;
background: #f5f5f5;
justify-content: center;
align-items: center;
}
img{
width: 200px;
height: 200px;
}
</style>
<body>
<div class="container">
<img src="./test.jpg" />
</div>
</body>

image.png
3 試試其他塊級元素呢?
<style>
.container{
width: 400px;
height: 400px;
display: flex;
background: #f5f5f5;
justify-content: center;
align-items: center;
}
.content{
width: 100px;
height: 100px;
}
.content1{
background: red;
}
.content2{
background: green;
}
</style>
<body>
<div class="container">
<div class='content1'>今天天氣好</div>
<div class='content2'>心情也好</div>
</div>
</body>

image.png
可以看到,塊級元素被居中之后變成了內聯(lián)元素,沒辦法設置寬高
3 有沒有辦法讓多元素垂直排列居中呢?
答案當然是有的,用到了flex-direction: column
<style>
.container{
width: 400px;
height: 400px;
display: flex;
background: #f5f5f5;
justify-content: center;
align-items: center;
flex-direction: column;
}
.content{
width: 100px;
height: 100px;
}
.content1{
background: red;
}
.content2{
background: green;
}
</style>
<body>
<div class="container">
<div class='content1'>今天天氣好</div>
<div class='content2'>心情也好</div>
</div>
</body>

image.png
通過上面的例子相信大家已經非常清楚了,文字,圖片或者多塊級元素居中現(xiàn)在非常簡單, 只需要display: flex;align-items: center; justify-content: center;三個屬性就可以了。如果還想讓多元素垂直排列的話,還可以加flex-direction: column屬性就OK了。
最后,今天就到這里了, 如果還有特別的興趣 可以去看看這幾個屬性的其他值,能讓你在布局的時候有更多的思路。
需要注意的是: 如果使用了flex-direction: column,那么align-items和justify-content的效果就相反!