2013年8月20日 星期二

Html div 水平垂直置中

今日在Google找資料key入了關鍵字:div 水平垂直置中,找到了以下這篇資料
CSS 教學 – 設定一個 div 水平置中和垂直置中
此篇是以圖片來做教學示範,所以您有需要可以看此篇,但建議您先看此篇,講解比較清楚。

而我今日想在網頁中將文字水平垂直置中,那麼要怎麼設定Html div標籤呢,因為文字在div標籤中會改變height、width,那如果將來要修改div裡面的文字這樣以後一定又要修改CSS或Html碼,所以自己就利用JQuery來計算位置自動去調整div位置,這樣將來就不需要修改CSS或Html碼,即使div增加了文字也不需要去調整。

前置作業:
  請自行到JQuery下載jquery-2.0.2.min.js

以下是Code,註解都在程式碼中,在此不再作解釋
Html:
<!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>div水平垂直置中</title>
<style type="text/css">
body {
background-color: #EEE; /*背景色*/
}
.BOX {
border: 2px solid #444;
box-shadow: 5px 5px 5px #666;

position:absolute; /*position制定位置*/
top:50%; /* top 座標為 50% */
left:50%; /* left 座標為 50% */
}
</style>
<!--引用JQuery檔jquery-2.0.2.min.js-->
<script type="text/javascript" src="js/jquery-2.0.2.min.js"></script>
<script type="text/javascript">
    $(function () {
 var h=$('#divbox').height(); //取得div標籤,id為divbox的高度
 var w=$('#divbox').width();  //取得div標籤,id為divbox的寬度
 //計算位移margin-top,margin-left數值
 var margin_top=-(h/2);
 var margin_left=-(w/2);
       
          //為div標籤,id是divbox加入CSS
 $('#divbox').css({'margin-top':margin_top,'margin-left':margin_left});
    });
</script>
</head>
<body>
<!--class="BOX"會套用CSS的.BOX-->
<div class="BOX" id="divbox">
    <h1 style=" text-align:center;">
    目前網頁未開放<br />
    Current page is not open.
    </h1>
</div>
</body>
</html>