The author of this article @Qiangu Yihao.

preface

The boss’s mobile phone received a red envelope, why the red envelope is not in the center?

How do I center a child element horizontally and vertically in a parent container? This problem must take an examination of, in actual combat development, also apply very much.

You might be able to write off several implementations. But most people’s writing is not standard enough, can not withstand the hammer. In other words: These are people who talk big in interviews, but don’t know what to write when they’re on the battlefield.

In this article, we’ll list a few common ways to write it, and eventually you’ll see which one is the most elegant.

Of course, I’ll give you some examples of real life situations in real applications to give you a taste of the charm of standard vertical center.

How do I center a line element (text, image, etc.) horizontally and vertically

The problem of centering inline elements is simpler.

The inline elements are horizontally centered

Set the parent container to:

    text-align: center;

Copy the code

The inline elements are vertically centered

Center a single line of text vertically by setting the line height of the text equal to the height of the box. Such as:

    .father {
        height: 20px;
        line-height: 20px;
    }
Copy the code

How do I center a block-level element horizontally and vertically

This paragraph is the core of the article. How do I center a block-level child element horizontally and vertically in the parent container? There are several ways to write it. Let’s take a look.

Margin: Auto

Horizontally centering an element in CSS is very simple: if it is an inline element, apply text-align: center to its parent container; If it is a block-level element, apply margin: auto or margin: 0 auto to itself.

Margin: auto auto auto auto Margin: 0 auto is the same as margin: 0 auto 0 auto. The four values correspond to upper right, lower left. The calculated value depends on the remaining space.

However, if you want to center an element vertically, margin: Auto doesn’t work.

Take this code for example:


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        .father{
            height: 500px;
            background: pink;
        }
        .son {
            width: 300px;
            height: 200px;
            background: red;

            margin: auto;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <script></script>
</body>
</html>

Copy the code

In the code above, the parent element and the child element are fixed width and height. Even in this case, if I set margin: Auto to the child element, the child element is not vertically centered.

Is there a good general practice?

Method 1: Absolute positioning + margin (need to specify the width and height of the child element, not recommended)


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .father{
            position: relative;
            min-height: 500px;
            background: pink;
        }
        .son {
            position: absolute;
            width: 200px;
            height: 100px;
            background: red;
            top: 50%;
            left: 50%;
            margin-top: -50px;
            margin-left: -100px;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son">The content of the child element</div>
    </div>
    <script></script>
</body>
</html>

Copy the code

We center the top left corner of the child element, then move it up half the width (50px) to achieve vertical center. The principle of horizontal middle is similar.

Disadvantages: The width and height of the child element must be specified to write the margin-top and margin-left attribute values.

However, in general, for elements that need to be centered, the width and height are determined by their content, and fixed width and height are not recommended.

Translate (No need to specify the width and height of the child element, recommended)


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .father{
            position: relative;
            min-height: 500px;
            background: pink;
        }
        .son {
            position: absolute;
            background: red;
            top: 50%;
            left: 50%;
            transform: translate(50%, 50%); }</style>
</head>
<body>
    <div class="father">
        <div class="son">The content of the child element</div>
    </div>
    <script></script>
</body>
</html>
Copy the code

This allows the child element to be centered vertically in the parent container without specifying its width and height. When percentage values are used in translate(), they are translated and moved based on the width and height of the element itself (the width and height are calculated dynamically).

Option 3: Flex Layout (to be improved)

Set the parent to Flex layout and add justify-content: center so that the child elements are horizontally centered; Add the attribute align-items: center to the parent container so that the child elements are centered vertically.

Code examples:


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .father{
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: pink;
        }
        .son {
            background: red;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son">The content of the child element</div>
    </div>
    <script></script>
</body>
</html>

Copy the code

The downside of this is that setting context-content: center and align-items: center causes all child elements in the parent to be vertically centered (if there are more than one). How can I make it better if I want to center one of the specified child elements?

Flex Layout + Margin: Auto

Margin: Auto; margin: auto; margin: auto; margin: auto; margin: auto; margin: auto; margin: auto And you’re done.

Code examples:


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .father{
            display: flex;
            min-height: 100vh;
            background: pink;
        }
        .son {
            margin: auto;
            background: red;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son">The content of the child element wants to be centered horizontally and vertically</div>
        <div class="son2">This element doesn't want to be centered horizontally and vertically</div>
    </div>
    <script></script>
</body>
</html>
Copy the code

Note that when we use Flex layout for the parent, the margin: Auto of the child makes it centered not only horizontally but vertically as well.

See article: Exploring the magic of automatic Margins in flex context

Typical application scenario of vertical center: Red envelope curtain/popover

Problem is introduced into

Take “popovers” as an example. Now everyone’s popovers are all over the place with various styles and layouts. But when I was in the company, before writing popovers for the first time, everyone always asked one question: “Isn’t there a standard for something so generic as popovers?” After that, quietly write their own personalized popover to go.

It is recommended that when you write popovers, no matter what, you should strictly use horizontal center and vertical center.

Don’t use the distance from the top of the screen to calculate the position of the popover. It’s too rough. Don’t let your boss think, “You’ve been writing front-end code for so long that you can’t even make a popover work?”

Mobile terminal, red envelope curtain/popover in the standard writing (very standard)

Mobile terminal scene, here provides a red envelope curtain/popover center writing. Notice, it’s strictly centered, very standard. Why mobile? Have you ever seen the PC web to send you a red envelope?

In actual combat development, the following code, can be directly taken to use. Detailed notes, very intimate.


      
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
        <title>Document</title>
        <style>
            /* The entire popover component */
            .component_popup {
                position: fixed;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                z-index: 100;
            }

            /* Mask the background */
            .popup_mask {
                position: fixed;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                background: rgba(0, 0, 0, 0.7);
            }

            /* Popover area (content + CLOSE) : strictly centered */
            .popup_content {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(50%, 50%); }/* Popover contents */
            .content_box {
                width: 15.45 rem;
                height: 19.32 rem;
                background: url(http://img.smyhvae.com/20191010_1500_red-packet.png) no-repeat;
                background-size: 15.45 rem 19.32 rem;
            }

            /* Popup close icon */
            .content_close {
                width: 1.25 em;
                height: 1.25 em;
                background: url(http://img.smyhvae.com/20191010_1500_close.png) no-repeat;
                background-size: 1.25 rem 1.25 rem;
                margin: 0 auto;
                margin-top: 0.5 rem;
            }
        </style>
    </head>
    <body>
        <div class="content">The page body in the default document flow</div>

        <div class="component_popup">
            <div class="popup_mask"></div>
            <div class="popup_content">
                <div class="content_box"></div>
                <div class="content_close"></div>
            </div>
        </div>
    </body>
</html>

Copy the code

Effect:

Supplement:

1. If you have a lot of popovers in your page, it is recommended to encapsulate the popovers as an abstract component.

2, any popover, need to solve the “scroll through” problem, this article is limited space, please refer to.

The last paragraph

Some implementations are simple, but they have to be tempered. We need to be respectful of every line of code, not superficial. Team development, not personality, but standards and norms.


If you think this article is valuable to you, please like it and pay attention to our official website and WecTeam. We have quality articles every week: