使用Css实现水平垂直居中
问题:假设有一个div,高宽都为200px,如何使得div内的内容水平居中?
很简单,设置该div的style.textAlign为center。
<div style="text-align:center;width:200px;height:200px;border:1px solid black;"> 水平居中示例。</div>水平居中示例。 问题:假设有一个div,高宽都为200px,如何使得div内的内容垂直居中?
<table width="200" height="200" style="border:1px solid black;"> <tr> <td valign="middle">哈哈哈</td> </tr></table>使用Table垂直居中
<table width="200" height="200" style="border:1px solid black;"> <tr> <td valign="middle"><img src="//img.reader8.net/uploadfile/jiaocheng/2014/0125/201401251856139027.png"/></td> </tr></table>
<table width="200" height="200" style="border:1px solid black;"> <tr> <td valign="middle"> <div> 使用Table垂直居中<br /> 使用Table垂直居中<br /> 使用Table垂直居中<br /> </div> </td> </tr></table>使用Table垂直居中
<div style="width:200px;height:200px;border:1px solid black;line-height:200px;"> 文字的垂直居中。</div>文字的垂直居中。 对于多行文字的div,纯css实现目前比较无奈,IE应该是没有办法做到。
<div style="width: 300; height: 200;border:1px solid #C0C0C0;_position:relative;display:table;"><div style="text-align:center;display:table-cell;_position: absolute;_top:expression((this.parentNode.offsetHeight-this.offsetHeight)/2);_left:expression((this.parentNode.offsetWidth-this.offsetWidth)/2);vertical-align:middle;">多行文字<br />垂直居中</div></div>多行文字
<div style="width:200px;height:200px;border:1px solid black;line-height:200px;display: table-cell;vertical-align:middle;*display: block;*font-size:175px;*font-family:Arial;"> <img src="//img.reader8.net/uploadfile/jiaocheng/2014/0125/201401251856139027.png" style="vertical-align:middle;"/></div>
<div style="width:200px;height:200px;border:1px solid black;"> <div style="left:50%;top:50%;width:100px;height:100px;margin:-50px -50px;border:1px solid blue;position:relative;"> negative margin实现的垂直居中。 </div></div>negative margin实现的垂直居中。