利用负margin实现元素居中

原理就是对当前元素的position设置为absolute并且相对于父元素定位,先设置left:50%;top:50%使当前元素的左上角处于父元素的中心位置,之后再应用负margin特性使其中心位于父元素的中心.

负margin特性:负的margin-top,margin-left将当前元素往上/左拉,覆盖其他元素;

负的margin-bottom,margin-right将当前元素的后续元素往上/左拉,覆盖当前元素;

例如:

<!DOCTYPE html> 
<htm>
<head>
    <title></title>
    <style type="text/css">
        #father
        {
            position:relative;
            200px;
            height:160px;
            border:1px dashed gray;
        }
        #son
        {
            position:absolute;
            top:50%;
            left:50%;
            margin-top:-30px;
            margin-left:-50px;
            100px;
            height:60px;
            background-color:Red;
        }
    </style>
</head>
<body>
    <div id="father">
        <div id="son"></div>
    </div>
</body>
</html>

  在这个例子中,先利用position定位使#son的左上角位于#father的中心,再设置#son的margin-top,margin-left为其自身height/width的一般的负值,这样就轻松将其中心移至父元素中心.

原文地址:https://www.cnblogs.com/wincent98/p/7128339.html