Dhrub Kumar Dhrub Kumar - 3 months ago 7
HTML Question

Center aligning a text horizontally and vertically in a div element


I have made a div of fixed height and I want the text to align both
vertically and horizontally in the div.

I tried using margin:auto and
text-align but it didn't help.

I am beginner HTML/CSS.


<!DOCTYPE html>
<html>
<body>

<div style="background-color:black;color:white;padding:20px; height:400px;">
<h2>London</h2>

</div>

</body>
</html>

Answer
h2 {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}