Sometimes, we want to position a div in the middle of the screen when the page is bigger than the screen with CSS.
In this article, we’ll look at how to position a div in the middle of the screen when the page is bigger than the screen with CSS.
How to position a div in the middle of the screen when the page is bigger than the screen with CSS?
To position a div in the middle of the screen when the page is bigger than the screen with CSS, we set the position of the div to fixed.
For instance, we write
#mydiv {
position: fixed;
top: 50%;
left: 50%;
width: 30em;
height: 18em;
margin-top: -9em;
margin-left: -15em;
border: 1px solid #ccc;
background-color: #f3f3f3;
}
to add the position: fixed;
style to the div with ID mydiv
to keep the div fixed on theg screen.
And then we set the top
and left
styles to 50% to center it on the screen.
Conclusion
To position a div in the middle of the screen when the page is bigger than the screen with CSS, we set the position of the div to fixed.