css水平垂直居中方法归纳总结

css水平垂直居中方法归纳总结

行级元素

单行文字水平垂直居中

html

<div>我要居中</div>

css

div{
    
    
    width: 100px;
    height: 100px;
    background-color: yellow;
    text-align: center;
    line-height: 100px;
}

块级元素

已知宽高(使用定位)

1.使用margin移动

定位之后使用margin-left移动子级宽度的一半,使用margin-top移动子级高度的一半

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
.father{
     
     
    width: 500px;
    height: 500px;
    border: 1px solid yellow;
    position: relative;
}
.son{
     
     
    width: 100px;
    height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
    background-color: green;
}
   
</style>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>
</html>

2.使用margin:auto

html

<div class="father">
        <div class="son"></div>
    </div>

css

.father{
    
    
    width: 500px;
    height: 500px;
    border: 1px solid yellow;
    position: relative;
}
.son{
    
    
    width: 100px;
    height: 100px;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background-color: green;
}

未知宽高

1.使用translate方法移动居中

html

<div class="father">
        <div class="son">
            <div style="width: 100px; height: 100px;background-color: green;"></div>
        </div>
</div>

css

.father{
    
    
    width: 500px;
    height: 500px;
    border: 1px solid yellow;
    position: relative;
}
.son{
    
    
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%)
}

2.使用flex布局居中

html

<div class="father">
        <div class="son">
            <div style="width: 100px; height: 100px;background-color: green;"></div>
        </div>
</div>

css

.father{
    
    
    width: 500px;
    height: 500px;
    border: 1px solid yellow;
    display: flex;
    justify-content: center;
    align-items: center;
}

猜你喜欢

转载自blog.csdn.net/sinat_40105935/article/details/111405359
今日推荐