DBMNG数据库管理与应用

科学是实事求是的学问,来不得半点虚假。
当前位置:首页 > 经验分享 > WEB

在css样式表通过设置position:absolute时实现元素水平居中

css使用布局元素中,除了float浮动,position设置网页布局是最常见的。当将position的值设置成绝对定位(absolute),该元素已经脱离常规文档流。使用margin: 0 auto;是无法让目标元素居中。

下面附上解决position: absolute;后居中的代码:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
 <meta charset="utf-8" />
 <title>测试</title>
 <style type="text/css">
 body, div, ul, ol, li, p {
 margin: 0;
 padding: 0;
 }
 body {
 font: 14px/1.4 "微软雅黑", "黑体";
 }
 a {
 text-decoration: none;
 color: #333;
 }
 ul, ol {
 list-style: none;
 }
 .nav {
 width: 980px;
 height: 50px;
 border: 1px solid #eee;
 border-radius: 4px;
 background-color: #5CB85C;
 position: absolute;
 top: 100px;
 left: 50%;
 width: 980px;
 margin-left: -490px;
 box-shadow: 0 3px 3px #ccc;
 }
 .nav li {
 float: left;
 margin-left: 20px;
 line-height: 50px;
 padding: 0 20px;
 }
 .nav li:hover {
 background-color: #398439;
 }
 .nav a {
 color: #fff;
 letter-spacing: 1px;
 }
 /*
 * css content
 */
 .content {
 width: 980px;
 margin: 0 auto;
 height: 900px;
 }
 </style>
</head>
<body>
 <div class="nav">
 <ul>
 <li><a href="#">志成网络营销中</a></li>
 <li><a href="#">首页</a></li>
 <li><a href="#">博客</a></li>
 </ul>
 </div>

 <div class="content">

 </div>
</body>
</html>

上面代码中,设置目标元素的固定宽度,left为50%;margin-left为目标元素固定宽度的一半。如下所示。

 left: 50%;
 width: 980px;
 margin-left: -490px;

总结:按照上面3行代码的思路,添加到设置了绝对定位的目标元素中即可水平居中显示。

 

本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号