1.水平居中:
<style> #parent{ width:300px;height:300px;background:#e5e5e5; } .child{width:150px;margin:0 auto;background:red;} </style> <div id="parent"> <div class="child"> today is a funny day! </div> </div>
2.垂直居中:
<style> #parent{ position:relative;height:300px;background:#e5e5e5; } .child{position:absolute;top:0;bottom:0;background:red;margin:auto 0;text-decoration:center;width:140px;height:20px;} </style> <div id="parent"> <div class="child"> today is a funny day! </div> </div>3.垂直居中还用vertical-align:middle;经常搭配父元素display:table-cell;使用