How to center a div vertically and horizontally
Overview
It is very essential to center a div horizontally and vertically on our web pages especially while making a card or image gallery.
- Horizontally centered: It means adding a
divin the middle of the container or page on the x-axis. - Vertically centered: It means adding a
divin the middle on the y-axis.
Horizontally centered
To center any div horizontally relative to any div or container, we just have to apply margin:auto and width which is relative to the containing element. Our styles should look like the following:
.middle{
background-color: green;
height: 300px;
width: 80%;
margin: auto;
}
See the code snippet and output below.
Explanation
-
Lines 1 and 19 : The start and close of the
htmltag. -
Lines 2–13 : We start the
headtag which contains thestyletag which contains the style for the.middlediv. -
Lines 14–17 : We have the
bodytag which contains thedivwhich is to be centered.
Vertically centered
To center the div element vertically, we just have to:
-
Give a postion value to our
diveither relative or absolute depending. -
Make the
top:50%;and -
Add a
transform:translatecoordinate values. We should have something like below.
.middle {
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
As you can see from the output above, our div is in the middle of the display pane vertically.
Explanation
-
Lines 1 and18 : The start and close of the
htmltag. -
Lines 2–12 : We start the
headtag which contains thestyletag which contains the style for the.middlediv. -
Lines 13–17 : We have the
bodytag which contains thedivwhich is to be centered.
Combination of both horizontal and vertical divs
We can combine the style blocks for the horizontal and vertical centering, to get a div which is centered on a page.
But then, we can apply this style below to achieve that in a much cooler way.
.middle{
width:90%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
Example
The code snippet below shows how a div can be placed at the center of a page.
Explanation
-
Lines 1 and 22 : The start and close of the
htmltag. -
Lines 3–16 : We start the
headtag which contains thestyletag. Thestyletag contains the style for the.middlediv. In this style thedivis given position absolute, with top and left distances of 50%, this will center thedivbut with some bias. But with thetransform: translate(-50%,-50%)piece thedivhappens to be position correctly at the center, eliminating the bias. -
Lines 17–21 : We have the
bodytag which contains thedivwhich is to be centered.