Summary of CSS horizontal and vertical centering method

Summary of CSS horizontal and vertical centering method

Row-level element

Single line text is centered horizontally and vertically

html

<div>我要居中</div>

css

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

Block element

Known width and height (using positioning)

1. Use margin to move

After positioning, use margin-left to move half of the child's width, and use margin-top to move half of the child's height

<!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. Use 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;
}

Unknown

1. Use the translate method to move the center

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. Use flex layout to center

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;
}

Guess you like

Origin blog.csdn.net/sinat_40105935/article/details/111405359