How to center a element inside div with css
Centering elements inside div is a common problem in web development. In this post I will explain a very easy solution for this that works always.
Before centering
Let’s say we have those 2 containers.
<div class="container">
<div class="center-element"></div>
</div>
<style>
.container {
width: 300px;
height: 300px;
background: red;
}
.center-element {
width: 200px;
height: 200px;
background: yellow;
}
</style>
Centering the element
The easiest way is to use the flex display that handles the centering in very good way.
We will modify our code as following:
<style>
.container {
...
display: flex;
justify-content: center; /* center horizontal */
align-items: center; /* center vertical */
...
}
</style>
Sources
- https://www.freecodecamp.org/news/how-to-center-things-with-style-in-css-dc87b7542689/
- https://www.w3schools.com/css/css_align.asp
Building something like this in production?
I help teams turn setups like this into reliable, monitored infrastructure.
Get a free consulting callGet my monitoring stack checklist
The exact checklist I use when setting up observability for a new team. No spam, unsubscribe anytime.