CSS实现文本高度不定的垂直居中方案

这种方式主要是针对文本高度不确定度情况,可能是一行或多行文本。
实现方式分两种情况,第一种是古董浏览器,IE6/7,第二种是现代浏览器IE8/9/FF/Chrome等。
IE6/7需要三个元素层:
外层是包裹层,也可以当为模块层,必要属性是position/height,
中间层是偏移层,必要属性是position/top:50%,
内层是文本层,必要属性是position/top:-50%。
设置top一正一负刚好抵消偏移,保证文本层始终在中间。

IE8/9/FF/Chrome不需要那么麻烦,只需要两个层,
外层同样是包裹层,必要属性:display:table,
内层是文本层,可直接包含文本,必要属性:display:table-cell/vertical-align:middle,
只需要简单的必要三个属性即可实现。

实例代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ie中垂直居中</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style type="text/css">
#div1{
        width:300px;
        position:absolute;
        border:1px solid #000;
           top:100px;
        left:200px;
        display:table;
}

.div2{
        display:table-cell;
        vertical-align:middle;
        *position:absolute;
        *top:50%;
}

span{
        *position:relative;
        *top:-50%;
}
button{
        cursor:pointer;
}
</style>
<script>
        function add(){
                var div1=document.getElementById('div1');
                var h=div1.offsetHeight;
                div1.style.height=h+30+'px';
        }
        function reduce(){
                var div1=document.getElementById('div1');
                var h=div1.offsetHeight;
                div1.style.height=h-30+'px';
        }
</script>
</head>
<body>
<div id="div1" style="height:200px">
        <div class="div2">
                <span>IE6/7使用定位关系来垂直居中,IE8/9使用display:table和display:table-cell</span>
        </div>
</div>
<button type="button" id="add" onclick="add()">增加高度</button><br/><br/>
<button type="button" id="reduce" onclick="reduce()">减少高度</button>
</body>
</html>

 

 

posted @ 2012-07-02 11:48  脉凌网络  阅读(429)  评论(0编辑  收藏  举报