One, horizontal center layout

Horizontal centered layout HTML looks like this:

<div class="parent">
    <div class="child">DEMO</div>
</div>
Copy the code

1, inline-block + text-align

Change the layout of the child element to inline-block, or the child element is a block-level element. To center the parent element, set text-align to center.

.child{
    display: inline-block;
}
.parent{
    text-align: center;
}
Copy the code

Note: the text-align attribute can be inherited. Therefore, we do not want the elements inside the child to be centered. We need to set the text-align of the child to left.

Margin: 0 auto

When using margin: 0 auto, note that the width of the child is its own width. You can set the CSS for child to be width: fit-content or display: table; You can also set the CSS of the parent to display: flex.

.child{
    margin: 0 auto;
    width: fit-content;
    // display: table;
}
Copy the code

Absolute + transform

.parent{
    position: relative;
}
.child{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}
Copy the code

Flex + context-content

.parent{
    display: flex;
    justify-content: center;
}
Copy the code

Two, vertical center layout

The HTML for the vertically centered layout looks like this:

<div class="parent">
    <div class="child">DEMO</div>
</div>
Copy the code

1. Table-cell + vertical-align

Set the parent element to a table cell, and then set vertical center to Middle.

.parent{
    display: table-cell;
    verticel-align: middle;
}
Copy the code

2. Absolute + transform

.parent{
    position: relative;
}
.child{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
Copy the code

Flex + align-items

.parent{
    display: flex;
    align-items: center;
}
Copy the code

4, the line – height

If the content is a single line of text, you can set the line height of the text to the height of the container

<div class="container">DEMO</div>
Copy the code
.container{
    height: 32px;
    line-height: 32px;
}
Copy the code

Three, horizontal + vertical center layout

The HTML for the center layout looks like this:

<div class="parent">
    <div class="child">DEMO</div>
</div>
Copy the code

1, inline-block + text-align + table-cell + vertical-align

Set the parent element to a table cell, and then set vertical center to Middle.

.parent{
    text-align: center;
    display: table-cell;
    verticel-align: middle;
}
.child {
    display: inline-block;
}
Copy the code

2. Absolute + transform

.parent{
    position: relative;
}
.child{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
Copy the code

Flex + align-items + context-content

.parent{
    display: flex;
    align-items: center;
    justify-content: center;
}
Copy the code