It is very essential to center a div
horizontally and vertically on our web pages especially while making a card or image gallery.
div
in the middle of the container or page on the x-axis.div
in the middle on the y-axis.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.
Lines 1 and 19 : The start and close of the html
tag.
Lines 2–13 : We start the head
tag which contains the style
tag which contains the style for the .middle
div.
Lines 14–17 : We have the body
tag which contains the div
which is to be centered.
To center the div
element vertically, we just have to:
Give a postion value to our div
either relative or absolute depending.
Make the top:50%;
and
Add a transform:translate
coordinate 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.
Lines 1 and18 : The start and close of the html
tag.
Lines 2–12 : We start the head
tag which contains the style
tag which contains the style for the .middle
div.
Lines 13–17 : We have the body
tag which contains the div
which is to be centered.
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%);
}
The code snippet below shows how a div
can be placed at the center of a page.
Lines 1 and 22 : The start and close of the html
tag.
Lines 3–16 : We start the head
tag which contains the style
tag. The style
tag contains the style for the .middle
div. In this style the div
is given position absolute, with top and left distances of 50%, this will center the div
but with some bias. But with the transform: translate(-50%,-50%)
piece the div
happens to be position correctly at the center, eliminating the bias.
Lines 17–21 : We have the body
tag which contains the div
which is to be centered.