We’ve all had that pesky HTML element that refuses to center no matter how many different CSS styles we apply. We always get it eventually, but sometimes it’s not before a lot of time has been wasted trying to remember different CSS rules about centering elements. If you currently happen to find yourself in a similar situation, here’s an overview of the basic CSS centering rules.
When centering text tags (paragraphs, headers, etc), all you have to do is apply one line of CSS to make the elements centered:
- p, h3{
- text-align: center;
- }
To center block elements (divs), you need to define the width of the element and set the left and right margins of the element to auto. The top and bottom margins can be set to whatever you like. Doing this using short code would look something like this:
- div{
- width: 250px;
- margin: 0 auto;
- }
Where it usually gets tricky is with inline elements, like images. This is because in order for margin: 0 auto to work on them, they need to be displayed as a block. Here’s how that code would look:
- img{
- display: block;
- width: 250px;
- margin: 0 auto;
- }
And if none of that helps you, you can also refer to this useful web app that generates CSS code to center any HTML element.