1.行高法line-height(适用于单行或较少几个文字)
设置文字的行高和容器的高度相同
<div id="div1"> 单行文本或几个字的垂直居中
div> <style> #div1{
width: 300px;height: 100px;/* 设置容器的宽高 */ margin: 100px auto;/* 使容器水平边距自动相等 */ border: 1px solid red;/* 给文本加上边框可以更清楚地看到效果 */ line-height: 100px; /*设置line-height与rongqi的height相等*/ text-align: center; /*设置文本水平居中*/ overflow: hidden; /*防止内容超出容器或者产生自动换行*/
style>

2.多行文本-内容填充padding
简单来说就是把文字挤到中间,此时容器高度不固定
<div id="div1"> 多行文本的垂直居中 多行文本的垂直居中 多行文本的垂直居中 多行文本的垂直居中 多行文本的垂直居中
div> <style> #div1{
width: 300px; margin: 100px auto;/* 使容器水平边距自动相等 */ border: 1px solid red;/* 给文本加上边框可以更清楚地看到效果 */ line-height: 100px; /*设置line-height与rongqi的height相等*/ text-align: center; /*设置文本水平居中*/ padding:50px 20px;}
style>

3.多行文本-用vertical-align,div模拟tabel
vertical-align只对有valign特性的元素才生效
<div id="div1"> <div id="div2"> 多行文本的垂直居中 多行文本的垂直居中 多行文本的垂直居中 多行文本的垂直居中 多行文本的垂直居中
div>
div> <style> #div1{
width: 300px;height: 200px; margin: 100px auto;/* 使容器水平边距自动相等 */ border: 1px solid red;/* 给文本加上边框可以更清楚地看到效果 */ display: table; } #div2{
display: table-cell; vertical-align: middle; text-align: center; width: 100%; }
style>

4.子容器的垂直居中-定位移动
子绝父相,根据子容器的大小进行定位移动
<div id="div1"> <div id="div2"> 子容器的垂直居中
div>
div> <style> #div1{
width: 300px;height: 200px; background-color: #ccc; position: relative; } #div2{
width: 100px;height: 100px; background-color: #FB7299; margin: auto; position: absolute; left: 50%;top:50%; margin-top: -50px;margin-left: -50px; }
style>

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/208371.html原文链接:https://javaforall.net
