首页 > 其他 > 详细

居中元素

时间:2014-09-11 18:49:02      阅读:255      评论:0      收藏:0      [点我收藏+]

1、居中一个浮动元素,关键是使用postion:relative;之后,再使用margin-left: width/2; 通过这样的方式让元素居中。

【注】position:relative;

   特性:(1)不使元素脱离文档流。文档流:即文档中可显示对象在排列时所占用的位置。

      (2)不影响元素本身的特性。

      (3)如果没有使用定位偏移量(top\right\left\bottom),对元素本身没有任何影响。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>让浮动元素居中</title>
    <style type="text/css">
        .center {
            float: left;
            width: 300px;
            height: 400px;
            background: red;
            position: relative;
            left: 50%;
            top: 50%;
            margin: 0px 0 0 -150px ;   /* margin-left 设置为宽度的一般,这样就能居中了 */
        }
    </style>
</head>
<body>
    <div class="center"></div>
</body>
</html>

 

 

2、让一个元素居中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>让浮动元素居中</title>
    <style type="text/css">
        .center{
            width: 500px;
            height: 400px;
            background: black;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="center"></div>
</body>
</html>

 

居中元素

原文:http://www.cnblogs.com/tracylyx/p/cssCenter.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!