Center align elements vertically and horizontally using CSS — Solved —
How to place the element horizontally and vertically center of its parent ?
Big Question and multiple solutions :
Solution 1 : Using Margin
Assume you have a width of 200px and height of 100px :
// SCSS Varaiables$width-val : 200px;
$height-val : 100px;.child-container {
position: absolute;
top: 50%;
left: 50%;
margin: -50px -100px;
width: $width-val;
height: $height-val;
}
Do you want to make it more generic ?
margin: calc((#{height-val} / 2) * -1) calc((#{width-val} / 2) * -1);
Solution 2 : Using Padding
This is one way of aligning center but not a good practice though.
.parent-container {
height: 600px; //Fixed height for parent
padding: 200px 0; //Fixed vertical padding for parent
}
.child-container{
margin: 0 auto;
height: 100%; // Child takes max height
}
Solution 3 : Using CSS Transform property
This is one of the most common technique.
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Solution 4 : Let’s use flex
I love this technique as its simple and elegant way. Magic of Flex :-)
.parent-container {
display: flex;
justify-content: center;
align-items: center;
}
Solution 5 : Magical CSS3 Grid :
There are two way of solving this using grid, both simple and easy methods
.parent-container {
display: grid;
}
.child-container {
margin: auto;
}
Now let use try another solution
.parent-container {
display: grid;
place-items: center;
}
Solution 6 : Using Table-cell
I am not a great fan of table-cell as i love using grid and flex. Let see how this works.
.parent-container {
display: table-cell;
vertical-align: middle;
}
.child-container{
margin: auto;
}
So now we have learned multiple ways to vertically and horizontally center align. Which one would you prefer ?