Center Element Using CSS

Tram Ho

Horizontally and vertically  is a common question used in interviews. Suppose there is a parent element containing 1 child element like this:

In this article we will look at different ways to center the element above the page:

  1. Use Flex
  2. Use Grid
  3. Use absolute position
  4. Use Table
  5. Using writing-mode
  6. Use the Table tab
  7. Use margin auto

1. Use Flex

When using flex, we can use justify-content or align-items to align if needed:

2. Use Grid

CSS Grid includes pretty much all the alignment options like flexbox, so we can use it on the parent element like this:

Or

3. Use absolute position

A simple trick using position absolute:

4. Use Table

A really simple approach and one of the first (before, everything was a table), is to use the behavior of table cells and vertical alignment to center an element. on the container.

5. Using writing-mode

writing-mode can change the way the text is displayed. For example, you can use writing-mode to change the display direction of the text to vertical.

6. Use the Table tab

You can also use table tags

7. Use margin auto

Use margin-auto on the child element, and display on the parent element:

Best way according to author is Using Flex (1) and Using Grid (2)

Source: dev.to

Share the news now

Source : Viblo