源代碼
點擊運行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>教程</title> <style> .center { height: 200px; position: relative; border: 3px solid green; } .center p { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } </style> </head> <body> <h2>居中</h2> <p>以下實例中,我們使用了 positioning 和 transform 屬性來設置水平和垂直居中:</p> <div class="center"> <p>我是水平和垂直居中的。</p> </div> <p>注意: IE8 及更早版本不支持 transform 屬性。</p> </body> </html>
運行結果