居中元素

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

【注】position:relative;

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

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

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

<!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>
原文地址:https://www.cnblogs.com/tracylyx/p/cssCenter.html