当前位置:Gxlcms > html代码 > css的div竖直居中总结_html/css_WEB-ITnose

css的div竖直居中总结_html/css_WEB-ITnose

时间:2021-07-01 10:21:17 帮助过:19人阅读

经常在写代码的时候碰到垂直居中的问题,我一般用的多的是绝对定位加负的margin或者display: table来实现居中。但是实际项目中,常常有一些特殊的情况,让上述方法使用起来并不是那么的靠谱。因此,更多行之有效的方法就显得尤为重要了。

说明部分

本文不考虑浏览器的兼容问题,仅仅是提供一些方法供参考,实际开发时请根据实际情况选择。特别是在现在流行的响应式页面中,高度不固定的情况下,可能部分效果不适合使用。能力有限,更多方法请联系我后期添加。

正文开始

为了方便下文说明,我们先统一html为:

子div居中

1. 子元素有高度的情况

1.1 绝对定位和负的margin:

这个方法使用绝对定位的 div,把它的 top 设置为 50%,margin-top 设置为负的 div 高度的一半。

#parent {    position: relative;    width: 600px;    height: 600px;    background-color: #ccc;}#child {    position: absolute;    top: 50%;    left: 50%;    height: 30%;    width: 50%;    margin: -15% 0 0 -25%;    background-color: #fff;}    

1.2 绝对定位和margin:auto:

这个方法使用了一个 position:absolute,有固定宽度和高度的 div。这个 div 被设置为 top:0; bottom:0。但是因为它有固定高度,其实并不能和上下都间距为 0,因此 margin:auto 会使它居中。

#parent {    position: relative;    width: 600px;    height: 600px;    background-color:#ccc;}#child{    position: absolute;    top: 0;    bottom: 0;    left: 0;    right: 0;    margin: auto;    width:100px;    height:100px;    background-color: #fff;}

1.3 清除浮动:

这种方法,在子div外插入一个div。设置此 div height:50%; margin-bottom为负的子div的height。子div清除浮动,并显示在中间。

更改上面的html为下面的:

子div居中

css为:

#parent{     width: 600px;     height: 600px;    background-color: #ccc;}#floater {    float: left;    height: 50%;    margin-bottom: -50px;    background-color: #f00;}#child {    clear: both;    width: 100px;    height: 100px;    margin: 0 auto;    background-color: #fff;}

2. 子元素自适应高度的情况

2.1 div 的显示方式设置为表格:

父div 的显示方式设置为表格,因此我们可以使用表格的 vertical-align

#parent {    width:600px;     height:600px;    display: table;    background-color:#ccc;}#child {    display: table-cell;    vertical-align: middle;    background-color:#0f0;}

2.2 css3的transform 的 translate 属性:

先将元素定位到容器的中心位置,然后使用 transform 的 translate 属性,将元素的中心和父容器的中心重合,从而实现垂直居中

#parent {      position: relative;    width: 600px;    height:600px;    overflow: hidden;    background-color:#ccc;}#child{    position: absolute;    top: 50%;    background-color: #0f0;    transform: translateY(-50%);}

使用 transform 有一个缺陷,就是当计算结果含有小数时(比如 0.5),会让整个元素看起来是模糊的,一种解决方案就是为父级元素设置 transform-style: preserve-3d; 样式:

#parent{    -webkit-transform-style: preserve-3d;      -moz-transform-style: preserve-3d;      transform-style: preserve-3d;}#child {      position: relative;      top: 50%;      transform: translateY(-50%);}

2.3 flexbox

使用 flexbox 实现水平和垂直居中,只需使用两条居中属性即可

#parent{     width:600px;    height:600px;    display: flex;    justify-content: center;    align-items: center;    background-color:#eee;}#child {    background-color: #0f0;}

前端初学者用作整理知识之用,错误之处请指正

人气教程排行