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 :
- Text-Align Method
- Margin Auto Method
- 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>
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 thescript
element orstyle
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.