How to Center Any HTML Element

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:

Join us in our newest publication:
  1. p, h3{
  2. text-align: center;
  3. }

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:

  1. div{
  2. width: 250px;
  3. margin: 0 auto;
  4. }

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:

  1. img{
  2. display: block;
  3. width: 250px;
  4. margin: 0 auto;
  5. }

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.

Share and Enjoy !

0Shares
0 0