How to Place a Div in the Middle of the Screen when It is Smaller than the Page
Solution with the CSS position property
To place your HTML <div> element in the middle of the screen, you need to use the CSS position property with its "fixed" value. This will keep the <div> in view even when you scroll down.
In the example below, we set both the top and left properties to "50%" and add width and height. Also, you need a margin-top with a negative number of the height half, and a margin-left with a negative number of the width half.
In the end, we add border and background-color to make our <div> more obvious.
Example of placing a <div> in the middle of the screen:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
#example {
top: 50%;
left: 50%;
width: 30em;
height: 18em;
margin-top: -9em;
margin-left: -15em;
border: 1px solid #666;
background-color: #b9faac;
position: fixed;
}
</style>
</head>
<body>
<div id="example"></div>
text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br>
</body>
</html>
This works when you know the size of the <div> you’re going to center.
Example of placing a <div> in the middle of the screen with the CSS transform property:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
#example {
top: 50%;
left: 50%;
width: 30em;
height: 18em;
transform: translate(-50%, -50%);
border: 1px solid #666;
background-color: #b9faac;
position: fixed;
}
</style>
</head>
<body>
<div id="example"></div>
text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br> text
<br>
</body>
</html>t