"How to center a div", the iconic question for frontend interviews. Although this question seems quite easy but can turn into hell if asked to do it in different approaches. So in this article, I am going to tell you about the different ways of centering a div.
1. Using Flexbox
This is the most common approach to center a div. The Flexible Box Layout Module makes it easier to design a flexible responsive layout structure without using float or positioning.
Applying the following properties on the .parent div will center the .child div vertically and horizontally.
.parent {
display: flex;
justify-content: center;
align-items: center;
}
Using flexbox and margin
Just give display:flex to the .parent div and margin:auto to the .child div.
.parent {
display: flex;
}
.child {
margin:auto;
}
2. Using Position
The position property specifies the type of positioning method used for an element. Here we will use position relative and absolute.
First set the position property relative to the parent element.
.parent{
position:relative
}
Then set the position of the .child element to absolute with top, left, and transform properties as below.
.child{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
3. Using Grid
The CSS Grid Layout Module offers a grid-based layout system, with rows and columns, making it easier to design web pages without having to use floats and positioning.
Applying the following properties to the .parent element will center the .child element.
.parent {
display: grid;
justify-content: center; /* centers horizontally*/
align-content: center; /*centers vertically*/
}
Using grid and place-items
By giving the properties display:grid and place-items:center to the .parent element will center the .child element.
place-items is a shorthand property for align-items and justify-items which allows us to align items in a grid layout system.
.parent{
display: grid;
place-items: center;
}
Using grid and margin
Just give display:grid to the .parent div and margin:auto to the .child div.
.parent {
display: grid;
}
.child {
margin: auto;
}
4. Using Width, margin, and padding
Using margin we can center the div horizontally and with padding, we can center the div vertically.
Note - If you use this approach, do not add height property to the parent div.
.parent{
width:250px;
padding:5rem 0
}
.child{
width: 150px;
height:150px;
margin:auto;
}
5. Using Tables
Using CSS styling, we can make elements,such as <div> tags behave like <table> and <td> tags.
Apply the following properties to the .parent div.
.parent {
display: table-cell;
text-align: center; /*horizontal*/
vertical-align: middle; /*vertical*/
}
Give display: inline-block property to the .child div.
.child {
display: inline-block;
}
These are the different ways to center a div. That's it for this article, I hope you found this article helpful and will help you in your next interview!!