0
点赞
收藏
分享

微信扫一扫

关于让元素垂直居中的几种css写法

关于让元素垂直居中的几种css写法_flex

在前端页面中经常会有垂直居中的排版布局,而在一些前端面试时,经常也会出关于让元素垂直居中,问你有几种方法来实现的问题。

下面就是我自己在实际开发中常用的几种css写法,大家可以参考,如果有比较新的方法,欢迎留言补充[笔芯]。


一、flex弹性布局

HTML代码

<div class="box">
<div class="contant"></div>
</div>

css代码

.box{
width: 100%;
height: 100vh;
display: flex; /* 启用flex弹性盒子 */
justify-content: center; /* 平行居中 */
align-items: center; /* 垂直居中 */
background-color: #f1f1f1;
}
.contant{
width: 200px;
height: 200px;
background-color: #dddddd;
}

渲染效果

关于让元素垂直居中的几种css写法_flex_02


二、绝对定位+css3属性

HTML代码

<div class="box">
<div class="contant"></div>
</div>

css代码

.box{
width: 100%;
height: 100vh;
background-color: #f1f1f1;
}
.contant{
width: 200px;
height: 200px;
background-color: #dddddd;
/* 绝对定位+transform属性 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}

渲染效果

关于让元素垂直居中的几种css写法_css_03


三、绝对定位+margin

HTML代码

<div class="box">
<div class="contant"></div>
</div>

css代码

.box{
width: 100%;
height: 100vh;
background-color: #f1f1f1;
}
.contant{
width: 200px;
height: 200px;
background-color: #dddddd;
/* 绝对定位+margin */
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}

渲染效果

关于让元素垂直居中的几种css写法_css_04


四、行高+内联块状元素

HTML代码

<div class="box">
<div class="contant"></div>
</div>

css代码

.box{
width: 100%;
height: 600px;
background-color: #f1f1f1;
line-height: 600px; /* 行高=高度 */
text-align: center; /* 水平居中 */
}
.contant{
width: 200px;
height: 200px;
background-color: #dddddd;
display: inline-block; /* 子元素为内联块状元素*/
}

渲染效果

关于让元素垂直居中的几种css写法_前端技术_05


五、网格系统+margin

HTML代码

<div class="box">
<div class="contant"></div>
</div>

css代码

.box{
width: 100%;
height: 100vh;
background-color: #f1f1f1;
display: grid; /* 网格系统grid */
}
.contant{
width: 200px;
height: 200px;
background-color: #dddddd;
margin: auto;
}

渲染效果

关于让元素垂直居中的几种css写法_前端技术_06

六、display: table-cell 仿表格单元格属性

HTML代码

<div class="box">
<div class="contant">文本信息</div>
</div>

css代码

.box{
width: 100%;
height: 100vh;
background-color: #f1f1f1;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.contant{
width: 200px;
height: 200px;
background-color: #dddddd;
display: table-cell;
text-align: center;
vertical-align: middle;
}

渲染效果

关于让元素垂直居中的几种css写法_flex_07


以上就是我常用的几种写法,还有一些其他的比如负边距离等,与上述中的某种类似,就不示例了。

一般的话,在实际开发中,你会2种其实也就够用了。

51cto / 公众号「 设计师工作日常 」,点赞关注。

举报

相关推荐

0 条评论