CSS Tips You Should Know Part I | Center
CSS Tips You Should Know Part I | Center

CSS tips and tricks for responsive design Part I | Centering in CSS

Elements in css – sounds simple, but quite complex. Every time I finished writing the center css and reread it: Why do I write this messy long coin just to do such a simple thing or that.

Hope that the following article can help people more in work and study.
Now which way do you need to center?

I. Horizontal

1. Fixed elements WIDTH and HEIGHT.

For a well-defined WIDTH AND HEIGHT element, we can use a negative MARGIN that is half the width of the child, then apply a POSITION of type ABSOLUTE, and give the LEFT value 50%. That should center it perfectly across a wide variety of browsers.

2. An undefined element WIDTH and HEIGHT.

With an undefined element WIDTH and HEIGHT, we can use POSITION and TRANSFORM to center an element.

3. For elements that are still INLINE- *.

For elements of the INLINE- * form (eg linkable, image, span, …) we simply use TEXT-ALIGN: CENTER.

4. For elements that are still BLOCK type.

For BLOCK elements (eg div, p, h1, h2, …) we simply need to use MARGIN-LEFT and MARGIN-RIGHT with auto values, which is also very quick to help you. center.

5. With more than one element.

5.1. If the elements are still INLINE- * form, we can still use TEXT-ALIGN: CENTER.

5.2. If the elements are still BLOCK, we can use the FLEX property to center them.

II. Vertically

1. Where the element is still INLINE-*

We have the following two useful ways to center vertically.


2. The element is also BLOCK type.

With the element still in BLOCK form, we will divide into 2 defined cases HEIGHT and undefined HEIGHT and the solutions respectively as follows:

2.1. Predefined HEIGHT:

Unspecified Height:

2.2. Using FLEXBOX.

III. Both horizontally and vertically.

1. Fixed elements WIDTH and HEIGHT.

For WIDTH and HEIGHT defined elements you simply sell the POSITION of type ABSOLUTE, and give TOP, LEFT value of 50%. Then give MARGIN-TOP AND MARGIN-LEFT with the WIDTH and HEIGHT tones of the sub-block.

2. Elements of unknown width and height

In this case we still use POSITION, TOP, LEFT as above, but instead of Margin, we will use TRANSFORM with TRANSLATE value (-50%, -50%);

3. Using FLEXBOX.

This is simple in all cases:

4. Using GRID.

The parent element has DISPLAY: GRID, then we just need to put MARGIN: AUTO in the child element, it will absolute center for you.