本文用三种方法实现垂直居中
第一种方法针对单行文字,用line-height实现,即将行间距设置为高度的一半,但是当文字多行时,该方法无效。
第二种方法针对定高多行文字,用<table>实现
第三种方法针对定高多行文字,用display:table实现
以下为代码(该代码实现了当鼠标放到左边的两个div上时,放大一倍,实现方法为在js中将对应的宽高都设置为2倍,并appendChild上去)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<style>
body{ margin:0; padding: 0; font-size:100px; font-weight: bold }
.left{ width:200px; height: 600px; position: absolute; left:0; top:0;}
.main{ height: 600px; margin:0 0 0 200px; background: #222; }
.left1{background: #EEE0E5;}
.left2{background: #EED5D2;}
/*单行实现*/
.left1,.left2{
height: 50%;
line-height: 300px; /*用行间距实现垂直居中,但只适合只有一行的元素,一但元素超过一行,会显示到div外面*/
text-align: center;
word-wrap:break-word; /*自动换行*/
/*overflow:hidden; */ /*超出部分自动隐藏*/
font-size: 16px;
}
/*多行定高,使用标签table*/
table{
width:100%;
height: 100%;
}
td{
width:100%;
height: 100%;
text-align:center;
}
/*多行定高,用display实现*/
.single {
height: 500px;
width:100%;
display: table;
background: #EEE0E5;
}
.a{
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
</head>
<body>
<div class="left">
<div class="left1" id="left1" οnmοuseοver="change(this)" οnmοuseοut="remove(this)">left1
</div>
<div class="left2" id="left2"οnmοuseοver="change(this)" οnmοuseοut="remove(this)">left2
</div>
</div>
<div class="main">
<table><tr><td>table实现垂直居中table实现垂直居中</td></tr></table>
</div>
<div class="single">
<div class="a">单独的一个div实现垂直居中</div>
</div>
<script type="text/javascript" >
function change(e){
var a='enlarge'+e.id;
var x=document.getElementById(a);
if(!x){
var h=e.clientHeight;
var w=e.clientWidth;
var c=e.innerHTML;
var f=e.fontSize;
var b=e.background;
var newE=document.createElement("div");
newE.id=a;
newE.style.position="relative";
newE.style.border="1px solid black";
newE.style.height=h*2+'px';
newE.style.width=w*2+'px';
newE.innerHTML=c;
newE.style.fontSize=f*2+'px';
newE.style.lineHeight=h*2+'px';
newE.style.background="#ccc";
newE.style.top= -h+"px";
e.appendChild(newE);
}
else{
x.style.display="block";
}
}
function remove(e){
var a='enlarge'+e.id;
var x=document.getElementById(a);
if(x)
x.style.display='none';
}
</script>
</body>
</html>