Sometimes it gets challenging to vertically align the element in middle of page. Two main CSS properties used in this tutorial are Position property and Transform property.
Table of Contents
First of all make a container for the element you want to align vertically. If your element is directly inside body tag then you can apply same styling to body tag, to vertically align your element in the middle.
HTML Code
In this example, there is a container div element with an Id outer. Then there is main element inside this container with an Id inner. Inside this you can put anything you want. I have used a heading tag h1.
Note: You can use Inline or Inline-Block elements or Block level elements.
<!DOCTYPE html>
<html>
<body>
<div id="outer">
<div id="inner">
<h1>This is Our Main Div Area.</h1>
</div>
</div>
</body>
</html>
CSS Code for Vertical Alignment
Outer Element CSS
Then set the Position Property of outer element to fixed which will make it static, with 100% width and height.
#outer
{
position: fixed;
width: 100%;
height: 100%;
}
Inner Element CSS
Then set the Position Property of inner element to absolute which means that it's position will now depend on outer element. I have set it's position values of Top and Left to 50%.
This will move inner element but it won't be exactly in the center. Now use Transform Property to translate it by -50% for both X and Y axis as shown in code below.
That's it, your element will be in middle now both vertically and horizontally and will always be in middle no matter what.
#inner
{
position: absolute;
top: 50%;
left: 50%;
background-color: #ddd;
border: 2px solid #000;
padding: 10px 10px;
transform: translate(-50% , -50%);
}
Demo
Video Tutorial
Watch video tutorial here.