记录一下自己常用的两种简单实现水平垂直居中的方法
文章目录
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>
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论