Xhtml+css實踐水平置中的設計方法

來源:互聯網
上載者:User

有個疑惑已久的問題,前段時間做CSS+div布局時候,發現水平讓一個元素置中十分容易margin:0 auto;然而要做到垂直置中卻沒有找到可行的方案,以下是新發現的解決方案,整理如下:

 

Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<style>
.center{width:200px; height:200px; top:50%; left:50%; position:absolute; margin:-100px 0 0 -100px; background:#FF0000}
.div{width:200px; height:200px; top:50%; position:absolute; left:50%; background-color:#0099FF}
</style>
<body>
<div class="center">我才是真正的水平且垂直據總</div>
<div class="div">我只是做到了讓左上方的頂點處於視窗的中心。</div>
</body>
</html>

效果縮圖如下:

注意紅色方塊的中心點是瀏覽器視窗的中心,或者說是body元素的中心位置。

 

個人理解:

在此,我說下我的個人理解,該正方DIV元素如果要真正置中的話,實際上要做到讓它的中心點置中才可以,用margin:-100px 0 0 -100px;實現讓元素左移100px,再上移100px,從而實現了真正的中心點置中,綠色方塊是沒有用margin:-100px 0 0 -100px;之前的效果,紅色部分是位移後的效果。如此是否可以總結一點:margin-left,margin-top取負值的時候可以實現某種意義上的相對定位呢?

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.