1. 子DIV在父DIV居中问题
<style type="text/css"> #outer{ height: 500px; width: 500px; background-color: yellow; position: relative; } #middle{ position: absolute; top: 50%; left: 50%; width: 200px; height: 200px; margin-top: -100px; margin-left: -100px; background-color: red; } </style> <div id="outer"> <div id="middle"> </div> </div>
这段代码的关键问题在于margin-left 和margin-right , 这两个属性的值为子DIV宽和高的一半。
2. 未知宽和高的DIV中图片居中
<style> #test { display: table-cell; *position: relative; width: 300px; height: 300px; text-align: center; vertical-align: middle; border: 1px solid red } #test p { *position: absolute; *top: 50%; *left: 50%; margin: 0; background: red } #test p img { *position: relative; *top: -50%; *left: -50%; vertical-align: middle } </style> <div id='test'> <p> <img src="#"> </p> </div>
3. 图片居中
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片水平垂直居中-前端小站</title> <style> .box { width:300px; height:300px; background:#ccc; text-align:center } span { height:100%; display:inline-block; vertical-align:middle } img { vertical-align:middle } </style> <script src='jquery-1.8.0.js'></script> </head> <body> <div class="box"> <img src="http://t3.baidu.com/it/u=1481340604,3053366708&fm=21&gp=0.jpg"/><span></span> </div> </body> </html>