Before start, we need basic knowledge around CSS attributes, units, and functions.
Our goal is centering vertically and horizontally the blue element above with calc CSS function. And we assume, it has predefined width and height.
We use margin-top and margin-left to do our job. Follow the sketch above, X is width and Y is height of the element need to be centered.
We can conclude the formula in snippet below.
margin-top: calc((100vh — Y)/2);
margin-left: calc((100vw — X)/2);
Let’s practice!
HTML code
<div class=”popup-container”>
<div class=”popup-content”>
<h1>POPUP Title</h1>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Veniam sint dolores molestiae eum, illo dolorum quasi accusantium facilis autem. Repudiandae.
</p>
</div>
</div>
CSS code
.popup-container {
width: 100vw;
height: 100vh;
background: #000000ac
}.popup-content {
font-family: sans-serif;
background: #ffffff;
box-sizing: border-box;
position: absolute;
height: 324px;
width: 40vw;
padding: 5%;
margin-left: auto;
margin-right: auto;
margin-top: calc((100vh — 324px)/2);
margin-left: calc((100vw — 40vw)/2);
}
Final result
Voilà!