The article is guideline to center an element horizontally and vertically center the web page with CSS in 2 ways - margin (auto) and display (flex).
Using margin to horizontally center an element
The way margin works when assigning the value auto left (margin-left: auto) or right (margin-right: auto) is to use the entire remainder of the element containing it.
________________________________________
|A |
| ______________ |
| |B | |
| |margin-left | |
| <-------------------> |auto | |
| |____________| |
|______________________________________|
________________________________________
|A |
| ______________ |
| |B | |
| |margin-right| |
| |auto | <-------------------> |
| |____________| |
|______________________________________|To make an element centered on another, you can use this property of margin using both margin-left: auto and margin-right: auto, this means the element inside will occupy the rest to set margins for 2 sides, these 2 margin settings will be equal, creating the effect of centering 1 element in the element containing it.
.B {
margin-left: auto;
margin-right: auto;
}
________________________________________
|A ____________ |
| |B | |
| <---------> | | <---------> |
| | | |
| |__________| |
|______________________________________|Using flex to center an element
Using the flex property, flex can center inner elements both horizontally and vertically. Set container element display: flex.
- If
flex-direction: rowjustify-content: center: horizontal centering inner element.align-items: center: vertical centering inner element.
- If
flex-direction: columnjustify-content: center: vertical centering inner element.align-items: center: horizontal centering inner element.
.A {
display: flex;
flex-direction: row;
justify-content: center;
}
________________________________________
|A ____________ |
| |B | |
| <---------> | | <---------> |
| | | |
| |__________| |
|______________________________________|Using margin or flex to center an element?
Most websites use margin-left: auto and margin-right: auto to center the web page. Therefore, frontend developers can use this approach.
display: flex has been supported since CSS3 and is now stable, so developers can consider changing this new way of doing things for more options and modernity.