垂直居中

1、假如让一个一直宽高的div相对浏览器可视区水平和垂直都居中,实现起来很简单:

div{position:absolute;width:400px;height:300px;top:50%;left:50%;margin:-150px 0 0 -200px;border:1px solid #ff0000;}

2、如果是左右两列布局,左侧就一标题需要垂直居中,右列的内容高度不固定。可以使用table布局;如果不用table可以借鉴上边的方法实现垂直居中,

<style type="text/css">
body,div,h2
{ margin:0; padding:0;}
div
{ position:relative; width:882px; padding-left:200px; margin:0 auto;}
h2
{ position:absolute; left:0; top:50%;}
</style>
<div>
<h2>垂直居中显示</h2>
内容<br />内容<br />内容<br />内容<br />
内容<br />内容<br />内容<br />内容<br />
</div>

3、js实现

<style type="text/css">
.wrap
{ width:1002px; margin:0 auto;}
#side
{ float:left; width:200px;}
#main
{ float:right; width:790px;}
</style>
<div class="wrap">
<div id="side">垂直居中显示</div>
<div id="main">
内容<br />内容<br />内容<br />内容<br />内容<br />内容<br />
内容<br />内容<br />内容<br />内容<br />内容<br />内容<br />
内容<br />内容<br />内容<br />内容<br />内容<br />内容<br />
</div>
</div>
<script type="text/javascript">
var height = document.getElementById('main').offsetHeight;
document.getElementById(
'side').style.height = height + 'px';
document.getElementById(
'side').style.lineHeight = height + 'px';
</script>





原文地址:https://www.cnblogs.com/bianyuan/p/2356192.html