DEV Community

David Frempong
David Frempong

Posted on

How I center a div

This is one of the most commonly asked questions, so here's how I do it.

 HTML: 
 <div class='circle'></div>

 CSS:
 .circle{
 height: 24px;
 width: 24px;
 border-radius: 50%;
 background: #618ed6;
 justify-content: center; 
      (justify's content in center of page)
 text-align: center;
      (any text will be aligned to center of page)
 margin: 0 auto;
      (creates an equal amount of margin on each side, centering the object)
 padding: 0;
      (I do this if necessary to help center the object)
     }
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
grahamthedev profile image
GrahamTheDev

Please fix this as you have marked it as beginners and it is wrong.

First you missed the all important display: flex in order for this to work.

Secondly you added margin and padding which are not necessary as part of centring an item using flexbox and just add confusion.

Thirdly your example uses a class of div as the selector. Please use a more descriptive class such as centred or remove the erroneous full stop before div if this is a typo and you intended targeting every div on the page (which would be a bad idea).

Finally you need to explain that this is added to the parent in order to centre the children it contains so the accompanying HTML would be really useful.

At least you managed to keep the meme alive, people still cannot centre a div! 🤣

Collapse
 
davidfrempong profile image
David Frempong • Edited

Thanks for the insight boss; I appreciate the help so I can keep learning.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
davidfrempong profile image
David Frempong

This is definitely an easier way; thank you!