In the world of CSS, centering an HTML div element seems like a simple task but how to precisely centre a div element in the middle of a web page has drawn an unending debate. Like myself, most developers have memorised every technique for centering a div just in case it comes up during an interview. In any case, where is centred division applicable? How does it operate?
The picture above shows how Twitter/X uses a centered div when your lose your internet connection on its web application. Here is the CSS declaration for centering a div:
#centerDiv {
width: 200px;
height: 200px;
background: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
The CSS declaration above is straight-forward, we set position of the div to absolute so as to remove from normal document flow, we set top and left properties to 50% so that div is centered on the middle of the page. The last declaration transform:translate(-50%,-50%)
is the critical in centering the div.
Lets dive deeper
Here is a a web page with two grid lines elements, intersecting at the center of the document. The point of intersection is where the div should be centered.
This how it looks without the last transform declaration: transform:translate(-50%,-50%);
I asked Google Bard AI to explain what transform:translate(-50%,-50%) does exactly and here is the explanation I got:
In conclusio, centering a div means positioning it perfectly to the middle of the web page and then ensuring the center of the div itself is aligned to the center of the web page i.e the intersection lines.
Here is the final code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Center Div</title>
<style>
body {
width: 100%;
min-height: 100vh;
margin: 0;
padding: 0;
border: 1px solid green;
}
#centerDiv {
width: 200px;
height: 200px;
background: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
/* we use flex box to center elements inside the div*/
display: flex;
flex-direction: column;
justify-content: center;
}
.vertical-line {
height: 1px;
border: none;
transform: rotate(90deg);
}
.horizontal-line {
position: absolute;
top: 50%;
height: 1px;
width: 100%;
border-collapse: collapse;
border: none;
}
</style>
</head>
<body>
<hr class="vertical-line" style="background-color: green; z-index: 100" />
<hr class="horizontal-line" style="background-color: green; z-index: 100" />
<div id="centerDiv">
<span
style="
color: white;
text-align: center;
font-size: 1.5rem;
font-weight: bold;
"
>
I am centered div</span
>
</div>
</body>
</html>
Top comments (0)