前言
我们都知道,固定高宽的div在网页中垂直居中很简单,相信大家也很容易的写出来,但是不是固定高宽的div如何垂直居中呢?我们在网页布局,特别是手机等web端网页经常是不固定高宽的div,那么这些div如何垂直居中呢?这篇文章,我总结一下。
固定高宽div垂直居中
如上图,固定高宽的很简单,写法如下:
position:absolute;left:50%;top:50%;width:200px;height:100px;margin-left:-100px;margin-top:-50px;
不固定高宽div垂直居中的方法
方法一:
用一个“ghost”伪元素(看不见的伪元素)和 inline-block / vertical-align 可以搞定居中,非常巧妙。但是这个方法要求待居中的元素是 inline-block,不是一个真正通用的方案。
html如下:
class="block"style="height:300px;">class="centered">haorooms案例题目haorooms案例内容,haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容
css如下:
/* This parent can be any width and height */.block{text-align:center;}/* The ghost, nudged to maintain