Analysis of the principle of centering elements with CSS

Analysis of the principle of centering elements with CSS

It is a very common requirement to set the horizontal and vertical center of an element in CSS. But even though it seems extremely simple to implement in theory, in practice it often stumps many people.

Centering an element horizontally is relatively simple: if it’s an inline element, apply text-align: center to its parent; if it’s a block-level element, apply margin: auto to itself.

However, if you want to vertically center an element, it is not so easy, and sometimes just thinking about it can make your scalp numb.

This article explains inline elements and block-level elements respectively, collects the currently popular implementation methods and analyzes the implementation principles for your convenience. One thing to note here is that no method is perfect. The key is to look at your own needs and analyze which implementation method is most appropriate.

Inline elements

First, let's write the basic code:

<div class="main">
    <span class="content">I want to center the inline element span</span>
</div>
.main {
    width: 300px;
    height: 300px;
    background-color: #50ba8b;
}

.content {
    background-color: #5b4d4e;
    color: #FFFFFF;
}

The div with class .main wraps the inline element span with class .content. Our goal is to center the .content element in the .main element.

Horizontal Center

text-align

It is relatively simple to horizontally center inline elements. We can simply add text-align: center; to .main. Now .main becomes:

.main {
    width: 300px;
    height: 300px;
    background-color: #50ba8b;
    
    text-align: center; /* Horizontally centered */
}

Implementation principle: Set the value of text-align to center, because this attribute specifies the horizontal alignment of the text in an element, so if it is set to center, the text will be horizontally centered.

Vertical Center

line-height

The vertical centering of inline elements is explained by dividing it into one line and multiple lines or replaced elements such as images.

If it is a line, we can use line-height to achieve it. At this time, the .main element CSS code becomes:

.main {
    width: 300px;
    height: 300px; /* optional*/
    background-color: #50ba8b;

    line-height: 300px; /* vertical center */
}

In fact, setting line-height can make the text vertically centered, and there is no need to set height at the same time. This is also a misunderstanding that has always existed.

Implementation principle: This method achieves vertical centering by using the "equal division mechanism of line spacing" in CSS, which also explains why this method is only applicable to one line of text.

Another point that needs to be explained is that the vertical centering achieved in this way is "approximate", not perfect, because the vertical centerline of the text glyph is generally lower than the vertical centerline of the real "line box", and because the font-size we usually use is relatively small, this deviation is not easy to detect, so it is perceived as vertical centering.

line-height and vertical-align

Next, let’s talk about how to achieve vertical centering of replacement elements such as multiple lines or images. Here we need to use both line-height and vertical-align to achieve this.

First wrap the text:

<div class="main">
    <span class="content">
        I want to center the inline element span <br>
        I want to center the inline element span
    </span>
</div>

Look at the modified CSS code:

.main {
    width: 300px;
    background-color: #50ba8b;

    line-height: 300px;
}

.content {
    display: inline-block;
    background-color: #5b4d4e;
    color: #FFFFFF;
    line-height: 20px;
    margin: 0 20px;
    vertical-align: middle;
}

Implementation principle:

  • Set the display of the .content element to inline-block. Its function is to reset the external line-height to a normal size while maintaining the characteristics of the inline elements, so that the vertical-align attribute can be set and a very critical "line box" can be generated. What we actually need is not this "line box", but a product that comes with each "line box" - a "ghost blank node", that is, an invisible "node" with a width of 0 that behaves like an ordinary character. With this "ghost blank node", our line-height: 300px; has an object to act on, which is equivalent to propping up an inline element with a height of 300px and a width of 0 in front of the .content element.
  • Because inline elements are baseline aligned by default, we adjust the vertical position of multiple lines of text by setting vertical-align: middle; on the .content element to achieve the desired "vertical centering" effect. This method is also suitable for the vertical centering effect of replaced elements such as images. Of course, the "vertical centering" here is also approximate, which is caused by vertical-align. For the specific reason, you can learn more about vertical-align: middle;.

Block-level elements

Still write the basic code first:

<div class="main">
    <div class="content">I want to center the block-level div</div>
</div>
.main {
    width: 300px;
    height: 300px;
    background-color: #50ba8b;
}

.content {
    width: 150px;
    height: 150px;
    background-color: #5b4d4e;
}

The div with class .main wraps the block-level div with class .content. Our goal is to center the .content element in the .main element.

position + margin: auto

The implementation code is as follows:

.main {
    width: 300px;
    height: 300px;
    background-color: #50ba8b;
    
    /*Key code*/
    position: relative;
}

.content {
    width: 150px;
    height: 150px;
    background-color: #5b4d4e;

    /*Key code*/
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}

Implementation principle:

  1. Set the .main element to relative positioning position: relative;, so that its child elements will be relative to it when they are absolutely positioned.
  2. Then set the .content element to absolute positioning position: absolute; and set its top, left, bottom, and right to 0. In this way, the size of the element is expressed as "formatted width and formatted height", which is the same as the "normal flow width" of <div>. It belongs to the external size, that is, the size automatically fills the available size of the parent element. However, since we set the width and height of the .content element at this time, the element is limited from automatically filling, so there is an extra 150px of space.
  3. Finally, we set the .content element to margin: auto;. At this time, according to the calculation rules of auto, the remaining space above, below, left and right is divided equally, so it is naturally centered.

position + margin-left/top

The implementation code is as follows:

.main {
    width: 300px;
    height: 300px;
    background-color: #50ba8b;
    
    /*Key code*/
    position: relative;
}

.content {
    width: 150px;
    height: 150px;
    background-color: #5b4d4e;

    /*Key code*/
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -75px;
    margin-top: -75px;
}

Implementation principle:

  1. Set the .main element to relative positioning position: relative;, so that its child elements will be relative to it when they are absolutely positioned.
  2. Then set the .content element to absolute positioning position: absolute; and set top: 50%;, left: 50%;, so that the upper left corner of the .content element is located in the center of the .main element.
  3. Finally, set the .content element’s margin-left: -75px; and margin-top: -75px; to move itself left and up by half of its width and height. This way, the center of the .content element is at the center of the .main element, naturally achieving the centering effect.
  4. The disadvantage of this method is that it requires the width and height of the .content element to be fixed.

position + translate

The implementation code is as follows:

.main {
    width: 300px;
    height: 300px;
    background-color: #50ba8b;
    
    /*Key code*/
    position: relative;
}

.content {
    width: 150px;
    height: 150px;
    background-color: #5b4d4e;

    /*Key code*/
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

Implementation principle:

  1. Set the .main element to relative positioning position: relative;, so that its child elements will be relative to it when they are absolutely positioned.
  2. Then set the .content element to absolute positioning position: absolute; and set top: 50%;, left: 50%;, so that the upper left corner of the .content element is located in the center of the .main element.
  3. Finally, set the .content element transform: translate(-50%, -50%); to move it left and up by half of its width and height, so that the center of the .content element is at the center of the .main element, naturally achieving the centering effect.
  4. The advantage of this method is that it does not require a fixed width and height for the .content element.

Flexbox

The implementation code is as follows:

.main {
    width: 300px;
    height: 300px;
    background-color: #50ba8b;

    /*Key code*/
    display: flex;
}

.content {
    width: 150px;
    height: 150px;
    background-color: #5b4d4e;

    /*Key code*/
    margin: auto;
}

Implementation principle:

  • Set the .main element display: flex;.
  • Then set the .content element to margin: auto; to achieve centering.
  • This is undoubtedly the best solution. We don’t need to set the .content element to absolute positioning, margin: auto can naturally work on the width and height, and we don’t need to set the width and height of the .content element, because Flexbox is designed specifically for this type of need.
  • The disadvantage is that the current browser support is lower than other methods.

Another benefit of Flexbox is that it can also vertically center anonymous containers (i.e. text nodes that are not wrapped by tags). For example, instead of setting the .main element to display: flex;, we can set the .content element to display: flex; and with the help of the align-items and justify-content properties introduced by the Flexbox specification, we can also center the text inside it (we can use the same properties on the .main element to center the .content element, but this is more elegant than the margin: auto method and also serves as a fallback).

.content {
    width: 150px;
    height: 150px;
    background-color: #5b4d4e;

    /*Key code*/
    display: flex;
    align-items: center;
    justify-content: center;
    margin: auto;
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

<<:  MySQL query optimization: causes and solutions for slow queries

>>:  Vue installation and use

Recommend

Use CSS's clip-path property to display irregular graphics

clip-path CSS properties use clipping to create t...

How to install nginx in docker and configure access via https

1. Download the latest nginx docker image $ docke...

JavaScript to display hidden form text

This article shares the specific code of JavaScri...

Pay attention to the use of HTML tags in web page creation

This article introduces some issues about HTML ta...

MySQL select results to perform update example tutorial

1. Single table query -> update UPDATE table_n...

A brief discussion on when MySQL uses internal temporary tables

union execution For ease of analysis, use the fol...

Detailed explanation of Vue mixin

Table of contents Local Mixin Global Mixins Summa...

Vue implements the question answering function

1. Request answer interface 2. Determine whether ...

Nginx compiled nginx - add new module

1. View existing modules /usr/local/nginx/sbin/ng...

HTML code to add quantity badge to message button

HTML code: <a onclick="goMessage();"...

Vue implements simple comment function

This article shares the specific code of Vue to i...

Summary of basic SQL statements in MySQL database

This article uses examples to describe the basic ...

CSS example code for implementing sliding doors

The so-called sliding door technology means that ...