Vertically Center a Div Using CSS

Vertically Center a Div Using CSS

Posted on November 24, 2014

There is no simple CSS command to center a group of elements vertically yet. So we have put together a tutorial to share how we have been doing it for years. This method will always work and covers all browsers!

HTML

The first step is setting up your HTML. You need a main container div that contains 2 sub divs. These are required to create the system that makes vertically centering anything possible. Once you set this up, you can put anything you want inside of the centered div and it will be dynamically centered.

<div class="container">
   <div class="vertical">
      <div class="centered">
         <h1>Title Here</h1><br>
         <p>This is where your content can go, no matter what you add it will center vertically inside the centered div. For more tips visit <a href="http://caputodesignz.com">Caputo Designz</a>.</p>
      </div>
   </div>
</div>

CSS

The next step is to create your CSS. This will allow you to give each element the proper positioning to create the vertically centered elements. We are going to set a height on our div to allow you to see the elements inside centering to the different heights. Below we are going to give you a piece of jQuery that will allow you to do a full screen container with the centered elements.


/*Core CSS*/
.container {
	background: #000;
	background-size: cover;
	height: 500px;
	width: 100%;
	position: relative;
	margin-top: -1px;
}
.vertical {
	display: table;
	height: 100%;
	left: 0;
	position: absolute;
	top: 0;
	width: 100%;
	z-index: 11;
}
.vertical .centered {
	text-align: center;
	display: table-cell;
	vertical-align: middle;
	color: #fff;
}

/*Extra Styling*/
.container {
  font-family: arial;
}
a {
  color:#eb671f;
}
.vertical .centered h1 {
	color: #fff;
	display: inline-block;
	padding: 15px;
	margin: 0px auto;
	padding: 0;
	font-size: 50px;
	line-height: 68px;
	font-weight: 400;
	max-width: 850px;
	text-align: center;
}
.centered p {
  font-size:18px;
  font-weight:normal;
}

jQuery

The jQuery section is optional and allows you to create a full screen section. This is great if you want to use this on your homepage or an area you want to have a large visual impact. To use this, just make sure your element classes match ours and that you have included jQuery on your site.


$(document).ready(function() {
	var bodyheight = $(window).innerHeight();
	$(".container").innerHeight(bodyheight);
 });

 Demo

To view a demo on CodePen Click Here.