Teach you how to achieve vertical centering elegantly (recommended)

Teach you how to achieve vertical centering elegantly (recommended)

Preface

There are many ways to center horizontally and vertically in CSS. The methods introduced in this article are very comprehensive and detailed. They are shared for your reference and learning. Let’s take a look at the detailed introduction below.

"We put a man on the moon 44 years ago, and we still can't vertically center something in CSS." --Jams Anderson

Whenever it comes to centering in web design, the most important thing is to center the element with its parent element. It sounds simple, but have you considered the many possibilities?

Simple: elements with known width and height

If you know both the width and height of an element and want to vertically center the element relative to its parent, using absolute positioning may be a good approach to achieve this.


Elements with known width and height

main{
    position: absolute;
    top: calc(50% - 3em); //Move up by 50% of the parent element's height and half of its own height left: calc(50% - 9em); //Move left by 50% of the parent element's width and half of its own width width: 18em;
    height: 6em;
}

Advanced: Elements of unknown width and height

But many elements on the page have unknown width and height.


Elements with unknown width and height

Expand based on absolute positioning.

When we use the translate() function to calculate percentage values, the conversion and movement are based on the height and width of the element itself.

The translate() function can move an element in a specified direction, similar to relative in position. Or to put it simply, using the translate() function, you can move an element from its original position without affecting any web components on the X or Y axis.

Therefore, you don’t need to hard-code the size of the element in the compiled code, as long as you use percentage-based CSS transformations to offset the element.

main{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate( -50%, -50% );
}

Absolute positioning is not suitable

When we don't want to use absolute positioning, we can still use translate() to move the element by half its width and height.

You can use margin to achieve the effect of movement.

main{
    width: 18em;
    padding: 13m 1.5em;
    margin: 50vh auto 0; //The outer margin uses vh as the unit, because the percentage value of margin is interpreted relative to the width of its parent element, so vh is used here
    transform: translateY( -50% );
}

Table-based layout

CSS table might be a good choice.

Because tables are not rendered like regular block-level elements. For example, when the element is 100% wide, the table will only occupy the width of the actual content, while the default block-level element will automatically occupy 100% of the parent element.

<table style="100%">
    <tr>
        <td style="text-align: center; vertaical-align: center">
            I am vertically centered!
        </td>
    </tr>
</table>

If you consider the semantics of the page, you can do this

.something-semantic {
    display: table;
    width: 100%;
}
.something-else-semantic {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

Inline Block

We could even consider using pseudo-elements.
If we make the pseudo-element take up 100% of the height of the parent element, then we set both the pseudo-element and the element we want to vertically center to vertical-align: center.

Then we can get the vertical centering effect.

This is a relatively hacky method.

.block {
  text-align: center;
  white-space: nowrap;
}
 
/* Extend the height to 100% */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be vertically centered can be of any width and height*/ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

A Flexbox-based solution

Flexbox usually allows us to better manipulate the layout of its child elements, for example:

  • If the element container does not have enough space, we can set them in the same line without calculating the width of each element;
  • You can quickly lay them out in one column;
  • It is convenient to align them to the left, right, center, etc. of the container;
  • The order in which they are displayed can be changed without modifying the structure;
  • If an element container is set to a percentage and the viewport size changes, you don't have to worry about breaking the layout by not specifying an exact width for the element, because each child element in the container can automatically be assigned a proportion of the container's width or height.

It is undoubtedly the best solution. Because Flexbox is designed specifically for this type of need 😄

body{
    display: flex;
    min-height: 100vh;
    margin: 0;
}
main{
    margin: auto;
}

When the text inside the centered element also needs to be centered:

main{
    display: flex;
    align-items: center;
    justify-content: center;
    width:18em;
    height: 10em;
}

Summarize

The above is the full content of this article. I hope that the content of this article will have certain reference learning value for your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support for 123WORDPRESS.COM.

refer to:

  • CSS Demystified
  • http://css-tricks.com/centering-in-the-unknown
  • CSS Transformations: http://w3.org/TR/css-transforms
  • CSS values ​​and units: http://w3.org/TR/css-values
  • CSS Flexbox Layout: http://w3.org/TR/css-flexbox

<<:  Some findings and thoughts about iframe

>>:  Implementation of dynamic rem for mobile layout

Recommend

How to unify the character set on an existing mysql database

Preface In the database, some data tables and dat...

Detailed explanation of writing and using Makefile under Linux

Table of contents Makefile Makefile naming and ru...

The difference between key and index in MySQL

Let's look at the code first: ALTER TABLE rep...

How to use native JS to implement touch sliding monitoring events

Preface I wrote a small demo today. There is a pa...

Detailed explanation of the execution principle of MySQL kill command

Table of contents Kill instruction execution prin...

CSS menu button animation

To write a drop-down menu, click the button. The ...

Angular Cookie read and write operation code

Angular Cookie read and write operations, the cod...

Summary of several common methods of JavaScript arrays

Table of contents 1. Introduction 2. filter() 3. ...

Analysis of the pros and cons of fixed, fluid, and flexible web page layouts

There is a question that has troubled web designe...

MySQL time types and modes details

Table of contents 1. MySQL time type 2. Check the...

Docker deployment of Kafka and Spring Kafka implementation

This article mainly introduces the deployment of ...

Summary of MySQL's commonly used database and table sharding solutions

Table of contents 1. Database bottleneck 2. Sub-l...

How to install and deploy gitlab server on centos7

I am using centos 7 64bit system here. I have tri...

Detailed tutorial on how to create a user in mysql and grant user permissions

Table of contents User Management Create a new us...