Why do we center a div inside a div element? Notice most of any website’s main content block always on the middle or a picture perfectly aligned on the middle.
There are a lot of ways to center a div inside a div. In this tutorial, I am going to show you two different ways to center a div element inside another.
These two videos might help you.
See also: Center Align Texts in Vertical Position
Continue reading below if you don’t want to watch the video.
Margin to center a div
Make the margin of the child div (the div inside the div) set to zero and auto.
- margin: 0 auto;
Notice the code above we have set the first value to zero. The zero value is the margin from the top and also from the bottom of the div. In the second value, we have not set a numeric value but an auto which makes the div go in the middle horizontally. It is the margin from left and right of the div.
Note: Make sure to set a width in your child and parent div for this to work. The parent div should have a greater width obviously.
Text Align to center a div
- text-align: center;
Telling the parent div to make its child’s text elements to center also makes the child div to center horizontally. As a result the texts inside our child div are also centered. Therefore, the last thing we need to do is to keep the text aligned to the left.
The solution, we should target the child div and add a CSS style but this time text alignment to the left or wherever you prefer.
See more amazing CSS videos on youtube: Garnatti one
In conclusion, the two CSS styling techniques are both great methods to use to align a child div element in the middle. The margin attribute is better than the other since it will make your code lesser and simpler.