DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> 前端技巧
div 與圖片水平垂直居中的多種寫法(跨瀏覽器相容)
編輯:前端技巧     

寫法一:純 CSS 層漂浮(適合登入頁)

用絕對定位把元素左上角挪到 50%,再用負 margin 拉回一半寬高,元素就精準落在正中央。

<style type="text/css">
#divcenter {
  position: absolute;   /* 讓層漂浮起來 */
  top: 50%;
  left: 50%;
  width: 300px;
  height: 300px;
  margin-top: -150px;   /* 必須是高度的一半 */
  margin-left: -150px;  /* 寬度的一半 */
  background: yellow;
  border: 1px solid red;
}
</style>

<div id="divcenter">this is a test</div>

寫法二:JS + CSS,不漂浮(適合登入頁)

<script type="text/javascript">
function cen() {
  var divname = document.all("testdiv");
  // 居中高度 = (頁面高度 - DIV 高度) / 2
  var topvalue = (document.body.clientHeight - divname.clientHeight) / 2;
  divname.style.marginTop = topvalue;
}
window.onresize = cen;   // 視窗尺寸變化時重新計算
</script>

<body style="height:100%; width:100%; text-align:center;" onload="cen()">
  <div id="testdiv" style="margin:0 auto; border:1px solid red; height:400px; width:400px;">
    DIV 居中演示
  </div>
</body>

寫法三:最簡短、相容性最好

<div style="position:absolute; top:50%; height:240px; border:1px solid red;
            margin:0 auto; margin-top:-120px; width:300px; left:50%; margin-left:-150px;"></div>

補充:讓圖片在 div 內水平垂直居中

利用 table-cell 搭配定位 hack,可同時兼顧 IE5.5~IE8 與 Firefox、Opera、Safari:

<style type="text/css">
.img_v {
  display: table-cell !important;
  display: block;
  position: static !important;
  position: relative;
  overflow: hidden;
  width: 400px; height: 400px;
  border: 1px solid #000;
  vertical-align: middle;
  text-align: center;
}
.img_v p {
  display: table-cell !important;
  display: block;
  margin: 0;
  position: static !important;
  position: absolute;
  top: 50%; left: 50%;
  width: 400px;
  margin-left: auto; margin-right: auto;
}
.img_v img {
  position: static !important;
  position: relative;
  top: auto !important;  top: -50%;
  left: auto !important; left: -50%;
}
</style>

<div class="img_v"><p><img src="https://www.jb51.net/images/logo.gif"></p></div>

現代專案其實不必這麼辛苦:flex 的 display:flex; justify-content:center; align-items:center; 三行就能完成,且不必知道元素尺寸;若只是單一行列置中,grid 的 place-items:center 更簡潔。上面幾種寫法的價值在於理解定位與盒模型的運作,以及維護舊系統時派得上用場。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved