How to align block elements to center using CSS ?
The “blocks” are known for taking full line space, forcing other elements to start on a new line. In other words, they have a width of 100% of the webpage or container holding the block. In this article, we are going to see how to block elements that usually behave and how to center them using CSS.
Block Elements Behaviour: Any element can be set to behave like a block by setting their display property to the block “display: block”. There are some other elements like headers, div tags which are by default block. So they take the full line or full width of the web page or container holding it. Even if our content is taking 20% of the width of the webpage still the block property will reserve the full 100% width of the web page or container holding it.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
How to center these block elements: We have seen that how this block element behaves, we observe that as they take full line width, to center them we only have the margin property that is controlling them horizontally.
The margin can control the position of the block element both horizontally and vertically. To center them, we can adjust the margin property such that it is placed in the center.
Note: We can see that the “text-align : center” is not centering the block elements. They are only centering the non-block or inline-block elements.
Center block elements using margin property: We need to specify the margin from left and right such that it looks centered. We do not need to do this manually, we have one property value “auto” which will automatically set the margin such that our block element is placed in the center. Use the below CSS property to center your block element.
Example 2: We have one image that has some space around it, so by default the non-block element will come next to the img tag and not on the next line. After setting the “display: block” property, we can make our image to block element. It can be centered using “margin: auto” property.
Note: The body tag has been set to the “text-align: center” property. We know that it is not affecting the block elements.