This little snippet of code will show you how to center content in a div horizontally and vertically using HTML and CSS.  This, in the past, used to be semi-difficult.  Now, using CSS flexbox display property, it’s actually quite easy.  First, we’ll create a simple HTML skeleton with a div that has a class called “centerMe” inside the body tag:

<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title>Center Content Horizontally and Vertically</title>
</head>

<body>
<div class=”centerMe”>
I will be centered in the div horizontally and vertically
</div>
</body>
</html>

Now that we have the starting HTML, we can add the CSS inside a style tag in the head tag.  The CSS will target the div on the page with the “centerMe” class.  Here it is:

<style>
.centerMe{
height:300px; /*this makes the div 300px tall*/
width:500px; /*this makes the div 500px wide*/
border:solid 1px black; /*this makes the div visible by giving it a solid border that is 1px thick and black*/
display:flex; /*this applies the flexbox display property to the div so we can use the properties below*/
align-items: center; /*this vertically aligns everything to the center*/
justify-content: center; /*this horizontally aligns everything to the center*/
}
</style>

The CSS is using the display property called flexbox which allows you to easily accomplish our task.  Once we add the CSS, the content should look like this inside the div:

center content in div horizontally and vertically

Here is the code in its entirety:

<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title>Center Content Horizontally and Vertically</title>
<style>
.centerMe{
height:300px; /*this makes the div 300px tall*/
width:500px; /*this makes the div 500px wide*/
border:solid 1px black; /*this makes the div visible by giving it a solid border that is 1px thick and black*/
display:flex; /*this applies the flexbox display property to the div so we can use the properties below*/
align-items: center; /*this vertically aligns everything to the center*/
justify-content: center; /*this horizontally aligns everything to the center*/
}
</style>
</head>
<body>
<div class=”centerMe”>
I am centered on the page horizontally and vertically
</div>
</body>
</html>

If you’d like to learn more check and sign up for our HTML/CSS/JavaScript Training. Have a great one!