一、根据子容器div大小设置偏移量使其垂直居中发布
1、方法:一先设置其水平和垂直偏移量分别为父级元素的50%(left/top)
二根据其本身大小将其向左向上移动一半大小(margin-left/margin-top)
html代码部分:

css 代码:
.block{
width: 900px;
height: 600px;
background-color: green;
position: relative;
margin: auto;
}
#wrap{
width: 300px;
height: 300px;
background-color: #1b6d85;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
}
二、不用考虑子容器的大小设置其垂直居中
2、方法:利用绝对定位absolute布局,父容器相对定位、子容器绝对定位。
给子容器设置margin:auto;上下左右偏移量分别为0;此方法不兼容IE6、IE7。
css代码:
.block{
width: 900px;
height: 600px;
background-color: green;
position: relative;
margin: auto;
}
#wrap{
width: 300px;
height: 300px;
background-color: #204d74;
margin:auto;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
三、 与第一种方法类似,都是先设置水平垂直偏移量为父级元素的50%
再者是根据css3中的transform属性设置translate值
需要注意的是transform是css3属性,注意浏览器兼容问题,IE9之前的版本都不支持。
.block{
width: 900px;
height: 600px;
background-color: green;
position: relative;
margin: auto;
}
#wrap{
width: 300px;
height: 300px;
background-color: #204d74;
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
-o-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
四、display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签。
目前IE8+以及其他现在浏览器都是支持其属性
与其他display属性类似,table-cell同样会被CSS属性破坏,例如float 、position:absolute;
所以用table-cell属性时尽量不要同时使用以上两种会使其破坏的属性;
设定了display:table-cell的元素对高度宽度敏感,对margin值无反应,响应padding属性,基本
可以说其就是一个它的标签元素了
.block{
width: 900px;
height: 600px;
background-color: green;
display: table-cell;
vertical-align: middle;
}
#wrap{
width: 300px;
height: 300px;
background-color: #204d74;
margin:0 auto;
}
五、此方法只需在父级元素样式设置时书写这三行代码
display: flex;设置弹性布局
justify-content: center;定义弹性盒子元素在主轴(横轴)的对齐方式
align-items: center; 定义弹性盒子元素在纵轴方向上的对齐方式
但是在IE兼容性不好,ie9以及以下浏览器版本都不支持
.block{
width: 900px;
height: 600px;
background-color: green;
margin: auto;
display: flex;
justify-content: center;/!*实现水平居中*!/
align-items: center;/!*实现垂直居中*!/
}
#wrap{
width: 300px;
height: 300px;
background-color: #204d74;
}
单行文本居中方法
html代码:
<div id="text">
单行文本居中
</div>
css代码:
#text{
width: 300px;
height: 200px;
margin: 100px auto;
border: 4px solid black;
line-height: 300px;
text-align: center;
overflow: hidden;/!*防止内容超出容器产生子弹换行*!/
}
多行文本居中:
1、父级高度元素不确定时
html代码:
<div id="text">
多行文本居中
多行文本居中
多行文本居中
多行文本居中
多行文本居中
</div>
css代码:
#text{
width: 300px;
margin: 100px auto;
border: 4px solid black;
padding: 150px 50px;
text-align: center;
}
2、父级元素高度确定时
html代码:
<div class="block">
<div id="text">
多行文本居中
多行文本居中
多行文本居中
多行文本居中
多行文本居中
</div>
</div>
css代码:
.block{
width: 300px;
height: 200px;
margin: 100px auto;
border: 4px solid black;
display: table;
}
#text{
display: table-cell;
vertical-align: middle;
text-align: center;
}
本文详细介绍了多种CSS方法实现单行、多行文本及div的垂直居中,包括设置偏移量、绝对定位、transform属性、display: table-cell以及Flexbox布局。同时,针对不同方法的浏览器兼容性进行了说明。

4420

被折叠的 条评论
为什么被折叠?



