Ever wished you could center the content of a DIV just by setting attributes on the DIV? It turns out that with the right CSS, you can!

The following CodePen demonstrates CSS that adds the “align” and “valign” attributes to the <div> tag. Click on the results pane and press the spacebar to see different examples of centered content.

See the Pen Centered DIV by jbanes (@jbanes) on CodePen.

The simple example of centering the content both vertically and horizontally is like this:

<div align="center" valign="middle" style="height: 100vh;">
    Centered
</div>

Note the style that sets the height of the div. If you want vertically centered content you need to provide your div with a height. Otherwise the element will be sized to the content and won’t have anywhere to be centered to. In this example we used 100vh to size the height of the div to fit the screen.

Here’s a table that shows the attribute combinations needed for each alignment on the screen.

align=left
valign=top
align=center
valign=top
align=right
valign=top
align=left
valign=middle
align=center
valign=middle
align=right
valign=middle
align=left
valign=middle
align=center
valign=middle
align=right
valign=bottom

After adding the CodePen CSS to your project, simply look up the alignment you want and then plug the attributes into your div tag. Easy as can be!

Need help with your projects? Book a call today for a FREE consultation!