CSS样式-position为absolute的情况下如何居中

时间:2024-02-22 20:53:19
第一步:设定top,left为50%
第二步:通过margin-left,margin-top设定负值
 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <style type="text/css">
        div {
            width: 300px;
            height: 300px;
            background-color: #f00;
            position: absolute;
            left: 50%;
            /* 用width/2 */
            margin-left: -150px;

 

            top: 50%;
            /* 用height/2 */
            margin-top: -150px;
            
            /* 当position为absolute时,用下面auto这种方式进行居中,不再起作用 */
            /* margin: 0 auto; */
        }
    </style>
</head>
<body>
    <div></div>
</body>
</html>