How To Center Any HTML Element in CSS the Right Way — Works Every Time

Use the Right Tool For the Job

<!DOCTYPE html>
<html>
<head>
</head>
<body><div>
<div>
<span>Hello World!</span>
</div>
</div>
</body></html>
...
<head>
<style>
</style>
</head>
...
...<body><div class="cont">
<div class="sub-cont">
<span>Hello World!</span>
</div>
</div>
</body>...
...
<head>
<style>
.cont {
width: 400px;
height: 400px;
background-color: white;
}
.sub-cont {
width: 200px;
height: 200px;
background-color: dodgerblue;
}
</style>
</head>
...
...
<style>
html,body {
height: 100%;
background-color: pink;
}
.cont {
width: 400px;
height: 400px;
background-color: white;
}
...

The Centering Code

...
<style>
html,body {
height: 100%;
background-color: pink;
display: flex;
align-items: center;
justify-content: center;
}
.cont {
width: 400px;
height: 400px;
background-color: white;
}
...
...
<style>
html,body {
height: 100%;
background-color: pink;
display: flex;
align-items: center;
justify-content: center;
}
.cont {
width: 400px;
height: 400px;
background-color: white;
display: flex;
align-items: center;
justify-content: center;
}
.sub-cont {
width: 200px;
height: 200px;
background-color: dodgerblue;
display: flex;
align-items: center;
justify-content: center;
}
</style>
...

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store