display:flex 实现水平垂直居中
通过display:flex
实现水平垂直居中主要依赖于justify-content
和align-items
justify-content
决定了子元素的水平位置,设置justify-content:center
即可实现子元素的水平居中align-items
决定了子元素的垂直位置,设置align-items:center
即可实现子元素的垂直居中,这里需要设置元素高度
.container {
display: flex;
height: 100%;
width: 100%;
background-color: #f0f0f0;
justify-content: center;
align-items: center;
}
text-align:center和line-height实现水平垂直居中
另一种简单实现水平垂直居中的方法就是利用text-align:center
实现元素的水平居中,以及通过设置元素的height
和line-height
相同来实现子元素的垂直居中
.runningDuck {
text-align: center;
background-color: burlywood;
height: 200px;
line-height: 200px;
width: 200px;
color:white;
}
实现效果
代码
<html>
<style>
.container {
display: flex;
height: 100%;
width: 100%;
background-color: #f0f0f0;
justify-content: center;
align-items: center;
}
.runningDuck {
text-align: center;
background-color: burlywood;
height: 200px;
line-height: 200px;
width: 200px;
color:white;
}
</style>
<body>
<div class="container">
<div class="runningDuck">水平垂直居中元素</div>
</div>
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。