使div水平、垂直居中

将要设置居中的元素上 、右、下、左 都设为0,再将margin值设为水平垂直居中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .main{
            /*必须有position:relative;*/
            position: relative;
            width: 100px;
            height: 100px;
            background-color: red;
        }
        .content{
            /*必须有position:absolute;*/
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom:0;
            margin: auto;
            background-color: blue;
            width:20px;
            height: 20px;
        }
    </style>
</head>
<body>
    <div class="main">
        <div class="content"></div>
    </div>
</body>
</html>

这里写图片描述

方法二:设置top和left为50%,再设置margin-top和left为负值(自己的一半)

.content{
            /*必须有position:absolute;*/
            position: absolute;
            top: 50%;
            left: 50%;
            width:20px;
            height: 20px;
            margin-top: -10px;
            margin-left: -10px;
            background-color: blue;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章