本文摘自PHP中文网,作者青灯夜游,侵删。
css让div垂直居中的方法:1、使用绝对定位和负外边距进行居中;2、利用伪元素和inline-block、vertical-align进行居中;3、利用table布局进行居中;4、使用固定定位和transform属性进行居中。

本教程操作环境:windows7系统、CSS3&&HTML5版、Dell G3电脑。
我们都知道,固定高宽的div在网页中垂直居中很简单,相信大家也很容易的写出来,但是不是固定高宽的div如何垂直居中呢?我们在网页布局,特别是手机等web端网页经常是不固定高宽的div,那么这些div如何垂直居中呢?这篇文章,我总结一下。
固定高宽div垂直居中(使用绝对定位和负外边距)

如上图,固定高宽的很简单,写法如下:
1 2 3 4 5 6 7 | position : absolute ;
left : 50% ;
top : 50% ;
width : 200px ;
height : 100px ;
margin-left : -100px ;
margin-top : -50px ;
|
不固定高宽div垂直居中的方法
方法一:伪元素和inline-block、vertical-align
用一个“ghost”伪元素(看不见的伪元素)和 inline-block / vertical-align 可以搞定居中,非常巧妙。但是这个方法要求待居中的元素是 inline-block,不是一个真正通用的方案。
html如下:
1 2 3 4 5 6 7 8 | < div class = "block" style = "height: 300px;" >
< div class = "centered" >
< h1 >haorooms案例题目</ h1 >
< p >haorooms案例内容,haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容</ p >
</ div >
</ div >
|
css如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | . block {
text-align : center ;
}
.block:before {
content : '' ;
display : inline- block ;
height : 100% ;
vertical-align : middle ;
margin-right : -0.25em ;
}
.centered {
display : inline- block ;
vertical-align : middle ;
width : 50% ;
}
|
方法二:用table布局
可以用table布局方法,但是这种方法也有局限性!
写法如下:
1 2 3 4 5 6 7 | < table style = "width: 100%;" >
< tr >
< td style = "text-align: center; vertical-align: middle;" >
Unknown stuff to be centered.
</ td >
</ tr >
</ table >
|
由于table写法比较费时,你也可以用div代替table,写法如下:
html:
1 2 3 4 5 | < div class = "something-semantic" >
< div class = "something-else-semantic" >
Unknown stuff to be centered.
</ div >
</ div >
|
css:
阅读剩余部分
相关阅读 >>
最全的css样式整理总结
css margin-right属性怎么用
什么是css的行内式?
css选择第几个子元素用什么选择器
css中的animation是什么
css如何让a标签不可点击
css怎么更改超链接字体颜色
css文字颜色渐变的三种实现方式(附代码)
css text-indent属性怎么用
样式表css有哪几种类型
更多相关阅读请进入《css》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » css怎么让div垂直居中