I'm trying to center a div on my screen by making its position absolute, setting its top value to 50%, and then subtracting the top margin by half of the div's height. I am using offsetHeight, but it seems that the height returned by the offsetHeight property is less than the actual height of the div element. (See screenshot below)
Is there a fix for this? Is there an alternative that I can do instead of this?
Thanks in advance.
The height returned by offsetHeight is 69 px instead of the actual height, which is 328.375px.
// Custom title
let customTitle = document.getElementById("title");
chrome.storage.sync.get("title", (result) => {
customTitle.textContent = result.title;
});
// Centering container
let container = document.getElementById("container");
container.style.marginTop = -container.offsetHeight / 2 + "px";
window.onresize = container.style.marginTop = -container.offsetHeight / 2 + "px";
pre {
color: white;
display: block;
font-family: 'Mulish', sans-serif;
font-weight: 800;
font-size: 96px;
margin-block-start: 0.2em;
margin-block-end: 0.2em;
margin-inline-start: 0px;
margin-inline-end: 0px;
}
.container {
position: absolute;
top: 50%;
left: 10%;
}
button {
width: 150px;
height: 50px;
border: none;
border: solid 2.7px white;
border-radius: 8px;
background: rgba(168, 166, 166, 0);
font-family: 'Mulish', sans-serif;
font-weight: 600;
font-size: 18px;
color: white;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Mulish:wght@600;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="blocked.css">
</head>
<body>
<div id="container" class="container">
<pre id="title"></pre>
<button id="unblockButton">
Unblock
</button>
</div>
<script src="blocked.js"></script>
</body>
</html>