记录一下自己常用的两种简单实现水平垂直居中的方法
display:flex 实现水平垂直居中
通过display:flex实现水平垂直居中主要依赖于justify-content和align-itemsjustify-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> 相关推荐
drdrsky 2020-06-16
PioneerFan 2020-06-10
HSdiana 2020-03-28
葉無聞 2020-03-23
lyg0 2020-03-07
冰蝶 2020-01-10
玫瑰小妖 2019-12-31
行吟阁 2019-12-08
aiolos 2016-04-15
loverlucky 2016-03-15
WebVincent 2019-07-01
云端漂移 2019-07-01
renpinghao 2019-06-30
kbkiss 2019-06-29