您好,欢迎来到欧百情感网。
搜索
您的当前位置:首页css的div竖直居中总结_html/css_WEB-ITnose

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

来源:欧百情感网


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

正文开始

为了方便下文说明,我们先统一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;}

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

Copyright © 2019- obaigo.com 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务