一般我們用 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>
試著改變視窗寬度,你會發現這個菜單始終穩穩地固定在視窗正中央。