Hello! Today I will cover different cases for centering elements in CSS3.
Centering an element inside a parent element.
Note: The width of the centered element must be less than the width of the container (parent) element, so we can center it.
1- Centering Block Elements.
2- Centering Non-block Elements.
Block elements are the element in which the display property is set to block.
For block elements, we can use the margin: 0 auto trick.
Basically, it sets the margin of the top and bottom to zero, and when the left and the right margins have the same value: auto, it means that the margins are distributed equally on both sides of the elements. That makes the element centered.
The width by default is set to auto, and auto for block elements is 100%, so we should change it.
This method can be used for both vertical and horizontal centering.
We will use the absolute positioning.
First, we set a reference point, which is the top-left point of the parent element, by setting the parent element’s positioning to relative.
Second, Shift the current element 50% right, and 50% down.
Shifting works with respect to the top-left point of the element, but we wanted to shift the element from its center.
To fix the previous problem, we shift the element 50% (of its total width) to the left, and 50% (of its total height) to the top by using the transform property.
By non-block elements, we mean text inside an element, inline element, or inline-block element.
We treat inline, and inline-block elements as text with respect to the parent element.
For a horizontal center, we will use text-align: center in the parent element.
Change the line-height of the parent to be equal to the height of the parent.
Then, change the vertical-align of the child to be middle, and the line-height of the child to be normal.
That's it for today! I really hope that you learned from it. Tell me about your thoughts in the comments.