您的位置:首页 > Web前端 > CSS

纯css多种方法实现div中单行文字、多行文字及嵌套div垂直水平居中

2014-04-24 15:30 1121 查看
学习过程中经常遇到要居中的问题,水平居中问题比较好解决,而垂直居中问题因为vertical-align经常失效,所以不容易实现,今天将自己总结的一些方法归纳于这边。

1.div中单行文字垂直水平居中。条件:外层div高度已经给定。代码如下:

<style type="text/css"> 
.div3{ 
border:1px solid red; 
text-align:center; 
height:200px; 
line-height:200px; 
width:300px; 
overflow:hidden; 
} 
</style> 
<div class="div3">

2.div中多行文字垂直水平居中。条件:无。代码如下:

<style type="text/css"> 
.div4{ 
border:1px solid red; 
width:400px; 
padding-bottom:20px; 
padding-top:20px; 
text-align:center; 
} 
</style> 
<div class="div4"> 
div中多行文字垂直水平居中
 
div中多行文字垂直水平居中
 
div中多行文字垂直水平居 
</div>

3.div中嵌套div,使得中间div垂直水平居中。条件:无。应用table模拟法。代码如下:

<style type="text/css"> 
.div1{ 
border:1px solid red; 
display:table-cell; /* 模拟表格法*/ 
vertical-align:middle; 
text-align:center; 
height:200px; 
width:200px; 
} 
.div2{ 
border:1px solid red; 
margin:auto; 
height:100px; 
width:100px; 
} 
</style> 
<div class="div1"> 
<div class="div2"></div> 
</div>

4.div中嵌套div,使得中间div垂直水平居中。条件:外层div和内层div的高度,宽度都已经限定。通过设定margin来使得div居中。代码如下:

<style type="text/css"> 
.div5{ 
border:1px solid red; 
height:200px; 
width:200px; 
} 
.div6{ 
border:1px solid red; 
height:100px; 
width:100px; 
margin:50px 50px auto auto; 
} 
</style> 
<div class="div5"> 
<div class="div6"></div> 
</div>

5.div中嵌套div,使得中间div垂直水平居中。条件:外层div高度,宽度不限定,内部div高度,宽度已知,且内外层div的position都必须为absolute。通过设定top,left,margin来使得div居中。代码如下:

<style type="text/css"> 
.div7{ 
position:absolute; 
border:1px solid red; 
height:50%; 
width:50%; 
} 
.div8{ 
border:1px solid red; 
height:100px; 
width:100px; 
position:absolute; 
top:50%; 
left:50%; 
margin-top:-50px; 
margin-left:-50px; 
} 
</style> 
<div class="div7"> 
<div class="div8">aa</div> 
</div>

以上就是我目前所知道的垂直水平都居中的方法,还有很多地方不足,比如ie6兼容性方面等等,希望大家能把自己知道的分享出来,让我这个新手多多学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  纯CSS效果 CSS3