DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> DIV十CSS布局 >> 布局實例
用 position:fixed 讓 DIV 水平居中
編輯:布局實例     

一般我們用 margin auto 讓元素居中,但當元素設為 position:fixed 時,這招就不管用了。本文示範如何讓固定定位的 DIV 依然水平居中。

關鍵程式碼

#topmenu_keleyi_com{
  position:fixed;
  left:0px;
  right:0px;
  width:706px;
  margin-left:auto;
  margin-right:auto;
}

原理是:同時設 left:0 與 right:0 把元素往兩側拉滿,再指定固定寬度並搭配左右 auto 邊距,元素便會在視窗中水平居中。

完整範例

<!DOCTYPE html>
<html>
<head>
<title>使 position:fixed 的 DIV 居中</title>
<style type="text/css">
#topmenu{
  position:fixed;
  left:0px; right:0px;
  width:706px;
  margin-left:auto; margin-right:auto;
  top:100px; height:50px;
  background-color:Red;
}
#topmenu ul{ margin:0px; padding:0px; }
#topmenu li{ float:left; list-style:none; margin-right:1px; width:116px; background-color:#e0f0e0; }
body{ margin:0px; }
</style>
</head>
<body>
<div id="topmenu">
  <ul><li>菜單一</li><li>菜單二</li></ul>
</div>
</body>
</html>

試著改變視窗寬度,你會發現這個菜單始終穩穩地固定在視窗正中央。

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