Akash Varma
Posted on March 31, 2020
Hello DEVelopers!!
We will see how to center an element in css using different ways.
For all the examples, I will be using below html as common one.
<div class="parent">
<div class="child"></div>
</div>
Using Position
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Using margin in position
margin: auto works only for horizontal alignment.
But we can make it to work in both directions using below code.
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
//by giving top,left,right,bottom values as 0 now child's width and height is exact to parent.
width: 800px; //assuming random width
height: 200px; //assuming random height
margin: auto; //margin auto works for both vertical and horizontal alignments
}
Using Flex
.parent {
display: flex;
align-items: center;
justify-content: center;
}
Using Grid
.parent {
display: grid;
justify-content: center;
align-items: center;
}
Using Table
.parent {
display: table;
width: 100px;
height: 100px;
}
.child {
display: table-cell;
vertical-align: middle;
width: 50px;
height: 50px;
text-align: center;
}
Using text-align to center horizontally
.parent {
display: block;
text-align: center;
}
.child {
display: inline-block; //key point
}
Using line-height to center vertically
It works fine if there is only one line.
.parent {
height: 200px;
}
.child {
line-height: 200px; //same value of parent height
}
Using margin as auto to center horizontally
.child {
width: 50%;
margin: 0 auto;
}
💖 💪 🙅 🚩
Akash Varma
Posted on March 31, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.