Skip to content

Instantly share code, notes, and snippets.

@Nitin-Daddikar
Created June 21, 2018 04:22
Show Gist options
  • Save Nitin-Daddikar/87427fd174ad85aa504fe3ab47895071 to your computer and use it in GitHub Desktop.
Save Nitin-Daddikar/87427fd174ad85aa504fe3ab47895071 to your computer and use it in GitHub Desktop.
Approaches to centering Div vertically and horizontally.
/*Approach 1 - transform translateX/translateY:*/
.centerDiv {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
/*Approach 2 - Flexbox method:*/
html, body, .centerDiv {
height: 100%;
}
.centerDiv {
display: flex;
align-items: center;
justify-content: center;
}
/*Approach 3 - table-cell/vertical-align: middle:*/
html, body {
height: 100%;
}
.parentDiv {
width: 100%;
height: 100%;
display: table;
text-align: center;
}
.parentDiv > .childDiv {
display: table-cell;
vertical-align: middle;
}
/*Approach 4 - Absolutely positioned 50% from the top with displacement:*/
html, body, .centerDiv {
height: 100%;
}
.centerDiv {
position: relative;
text-align: center;
}
.centerDiv > p {
position: absolute;
top: 50%;
left: 0;
right: 0;
margin-top: -9px;
}
/*Approach 5 - The line-height method*/
.parentDiv {
height: 200px;
width: 400px;
text-align: center;
}
.parentDiv > .childDiv {
line-height: 200px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment