Md Toy Blog

CSS centering of content

Tue Feb 05 2019 00:00:00 GMT+0000 (Coordinated Universal Time)

One of the more common things to be done in CSS is trying to position content relative to the rest of the page.

There is this great article from Stephen Sun to whom I gave at least 1k claps. You should definitely read it.

He has compiled 3 ways for centering a div :

  1. Text-Align Method
  2. Margin Auto Method
  3. Absolute Positioning Method

Which way to use ?

In order to choose which way to do it answer the following questions.

Does your div have :

  • [] a parent whose center is your targeted center ?
  • [] a predefined width ?
  • [] to be centered horizontally ?
  • [] to be centered vertically ?

 1. Text Align Method

  • horizontal centering
  • parent's center is the target position

To use this method you have to be able to text-align: center the parent div. Assuming the parent's div center is where you want to place your centered child div.

<div class="my-parent-div">
    <div class="put-the-center-of-this-div-at-parent-center">Hello</div>
</div>

text

To center this you need to:

.my-parent-div {
    text-align: center;
}

.put-the-center-of-this-div-at-parent-center {
    display: inline-block;
}

If you do not set the display: inline-block then the child div will have the default display: block which will make it take the full available width. Every element in CSS has a default value for each of their properties. Regarding the display property, there are a ton of possible values (none, block, inline, list, table, flex, grid, ruby, etc.) and some can be combined. A few important ones are:

  • none makes the element not be displayed and not take any space in the flow (default value for the script element or style etc.
  • block makes the element take the full width available from parent container (default value for div or body)
  • inline makes the element not be displayed as a block, for example the span or a elements to allow them to be placed alongside text.