3 Methods to center your contents in your code

Centering stuff can be daunting task to do at times.

2 July,2021

post-image

Centering in HTML can be very easy just using the text-align property but a different thing when it comes to centering <div> elements. In this tutorial i wil show you the 3 methods used to center divs.

Uing FlexBox

This method is actually my favorite method of centering div elements using the Display flex property.

There are two main takeaways here to easily understand this mehtod.

1. There are always two or more block-level elements that you want to flex/center.

2.The flex property is applied to the top element i.e,the main/parent element containing all the other elements

The HTML

Your html should be something like in the picture.

post-image

The CSS

The CSS is prety straight forward, add margins and paddings modify it to your taste and should look like in the picture.If you don't know about flexbox no worries I will be making a tutorial on it soon but for now you can checkout the official docs on the MDN docs website which is pretty simplified for beginners.

post-image

The Result

If correcty witten you should be able to have similar result to the picture below

post-image

Further

By default flexbox will align the container in a row and ofcourse centering them but if you want it center aligned and in a column form, the column property is used and will give the result below:

post-image

The CSS

post-image

Thanks for Reading!

Contact Me :

social-media icon social-media icon social-media icon social-media icon social-media icon social-media icon social-media icon social-media icon