N ways to center elements with CSS

N ways to center elements with CSS

Preface

I can still vividly remember the time when I first started working and was completely tortured by the interviewer's series of questions. "How do you center the text?" "What if it is multiple lines of text?" "How do you achieve horizontal centering of block-level elements?" "How do you achieve vertical centering of block-level elements?" . . After being asked so many questions, my mind was a mess and I didn't know how to answer the questions I knew. Centering is an inevitable scenario in daily work and also appears frequently in interviews. This article will focus on these issues, hoping to help students who have the same doubts as I did back then, so that they can be more comfortable with centering issues in future work and interviews.

Centering inline elements

Center text vertically

Vertically center a single line of text

Vertically centering a single line of text is the simplest way to do this: set the line-height to the same as the box height.
There is a misunderstanding here. Many people set the height and line-height to be the same when centering a single line of text. In fact, there is no need to set the height. Just set the line-height. At this time, the height of the box is supported by the line-height, which is exactly the same as the line-height.

.center {
  // You don't need to set the height // height: 20px;
  line-height: 20px;
}

Vertically center multiple lines of text
1.vertical-align

vertical-align can specify the vertical alignment of inline elements.

This method requires adding an additional .center element to wrap the content that needs to be centered. Set the parent element's line-height to the element's height, and set the display of the centered child element .center to inline-block, so that it has the characteristics of an inline element. Because of the inheritance of line-height, set line-height: 20px; reset the centered child element's line-height, and then set vertical-align: middle; to align it vertically in the center of the line box.

<div class="box">
 <div class="center">
  Although you are playing the roles of passers-by A, B, C, and D, you still have life and soul.
 </div>
</div>
<style>
.box {
 background-color: orange;
 line-height: 200px;
 width: 300px;
}
.center {
 background-color: green;
 line-height: 20px;
 display: inline-block;
 vertical-align: middle;
}
</style>

2.table-cell
Different from setting vertial-align on inline elements, which will vertically center the current element, setting vertial-align on table-cell elements will vertically center its child elements. Even if the child elements are block-level elements, they will be vertically aligned. So this method can also be used if you want to vertically center block-level elements.

.box {
       height: 200px;
       display: table-cell;
       vertical-align: middle;
}

Center the elements horizontally

Text-align controls the horizontal alignment of elements within a sub-row. This is very simple, just set text-align: center.

.center {
       text-align: center;
}

Horizontally center block-level elements

The margin value of auto can occupy all the remaining space in the corresponding direction. If the margin values ​​in both horizontal directions are set to auto, the remaining space will be divided equally in the two directions, thus achieving centering.
So why do we never use this method to achieve vertical centering? Because there is a prerequisite for the auto value to take effect, that is, if no specific length is set in the corresponding direction, it will be automatically filled. Obviously, width can fill the parent element, but height cannot.

.center {
 margin: 0 auto;
}

Vertically center block-level elements

Can we use margin:auto; to achieve vertical centering? Of course you can. You can change the flow of the blocks by modifying the writing-mode and making them flow horizontally. In this case, the height direction will be filled by default. Setting margin:auto; can achieve vertical centering. However, this method has side effects. Because the writing-mode property is inheritable, it will cause all child elements under this element to change their flow direction to horizontal. And this method can no longer be used to achieve centering in the horizontal direction.

<div class="box">
    <div class="center"> 
        Although you are playing the roles of passers-by A, B, C, and D, you still have life and soul.
    </div>
</div>
<style>
.box {
 background-color: orange;
 height: 200px;
 writing-mode: vertical-lr;;
}
.center {
 background-color: green;
 height: 50px;
 margin: auto 0;
}
</style>

Is it possible to use this feature to achieve both vertical and horizontal centering? Yes, we can. Let’s continue to look down.

Horizontal and vertical center

1.position (center element with fixed width and height)
Set the parent element to absolute positioning and the centered element to relative positioning. The values ​​of top, right, bottom, and left are all 0. If you do not set a specific width and height, the centered element will fill the parent element both horizontally and vertically. At this time, setting the specific width and height with margin:auto; can achieve absolute centering.

It should be noted that this method is only compatible with IE8 and above browsers. If the project needs to be compatible with IE7, you can use the following method

.box {
 position: relative;
}
.center {
 position:absolute;
 width: 200px;
 height: 200px;
 top:0;
 bottom:0;
 left:0;
 right:0;
 margin: auto;
}

2.vertacal-align
First, we center the element horizontally and set the display value of the element to inline-clock so that it has the characteristics of an inline element. Set text-align: center; on the outer box element to center the centered element horizontally.
Then, to achieve vertical centering, you need to add an auxiliary element and set the auxiliary element height: 100%; so that the height of the current line box fills the parent element, and then set vertical-align: middle; to align it in the vertical center.

<div class="box">
    <div class="assist"></div>
    <div class="center"> 
        Although you are playing the roles of passers-by A, B, C, and D, you still have life and soul.
    </div>
</div>
<style>
.box {
    background-color: orange;
    height: 200px;
    width: 500px;
    text-align: center;
}
.center {
    background-color: green;
    width: 150px;
    display: inline-block;
    vertical-align: middle;
}
.assist {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
</style>

3. Position and margin
This method is suitable for situations where the width and height of the centered element are known. Set the relative positioning of the parent element and the absolute positioning of the centered element. The left and top values ​​are both 50%. The left and top values ​​are calculated relative to the width and height of the parent element respectively. At this time, the upper left vertex of the centered element will be located in the center of the parent element. Then set the margin-left and margin-top of the centered element to the negative half of its width and height, so that the centered element is offset to the left by 50% of its width in the horizontal direction and offset upward by 50% of its height in the vertical direction, thus achieving the centering effect.

<div class="box">
    <div class="center"> 
        Although you are playing the roles of passers-by A, B, C, and D, you still have life and soul.
    </div>
</div>
<style>
.box {
    background-color: orange;
    height: 200px;
    width: 500px;
    position: relative;
}
.center {
    background-color: green;
    width: 150px;
    height: 50px;
    position:absolute;
    top:50%;
    left:50%;
    margin-left: -75px;
    margin-top: -25px;
}
</style>

4. Position with transform
The fourth method is to use position with transform. This method is similar to the previous one in principle, but it adds elements with non-fixed width and height to the usage scenario. Similarly, first set the relative positioning of the parent element, the absolute positioning of the centered element, and the left and top values ​​​​to 50%. Then set the center element transform: traslate(-50%, -50%);, the percentage value of translate is calculated relative to itself, so that the center element is offset to the left by 50% of its width in the horizontal direction and offset upward by 50% of its height in the vertical direction, so that the centering effect can be achieved.

<div class="box">
    <div class="center"> 
        Although you are playing the roles of passers-by A, B, C, and D, you still have life and soul.
    </div>
</div>
<style>
.box {
    background-color: orange;
    height: 200px;
    width: 500px;
    position: relative;
}
.center {
    background-color: green;
    width: 150px;
    position:absolute;
    top:50%;
    left:50%;
    transform: traslate(-50%, -50%);
}
</style>

5.Flex
If you do not need to consider compatibility with IE9 and earlier browsers, flex layout is the most recommended method.
Set the parent element to a flex container, and set the main axis and cross axis alignment to center. For relevant knowledge about flex, you can refer to Mr. Ruan’s blog, which introduces it in great detail.

.box {
    display: flex;
    align-items: center;
    justify-content: center;
}

This concludes this article about N ways to center elements with CSS. For more information about centering elements with CSS, please search previous articles on 123WORDPRESS.COM or continue browsing the related articles below. I hope you will support 123WORDPRESS.COM in the future!

<<:  Summary of how to use the MySQL authorization command grant

>>:  Solution to PHP not being able to be parsed after nginx installation is complete

Recommend

Six-step example code for JDBC connection (connecting to MySQL)

Six steps of JDBC: 1. Register the driver 2. Get ...

How to build your own Angular component library with DevUI

Table of contents Preface Creating a component li...

CSS to achieve Cyberpunk 2077 style visual effects in a few steps

background Before starting the article, let’s bri...

Solution to Docker image downloading too slowly

Docker image download is stuck or too slow I sear...

js canvas implements verification code and obtains verification code function

This article example shares the specific code of ...

Detailed installation and use of virtuoso database under Linux system

I've been researching some things about linke...

Research on Web Page Size

<br />According to statistics, the average s...

How to implement a lucky wheel game in WeChat applet

I mainly introduce how to develop a lucky wheel g...

Detailed explanation of the core concepts and basic usage of Vuex

Table of contents introduce start Install ① Direc...

MySQL Basic Tutorial: Detailed Explanation of DML Statements

Table of contents DML statements 1. Insert record...

DOM operation table example (DOM creates table)

1. Create a table using HTML tags: Copy code The ...