Skip to content

Instantly share code, notes, and snippets.

@gokulkrishh
Last active February 7, 2022 15:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gokulkrishh/9ff9c05300634088d8268d255f2783e1 to your computer and use it in GitHub Desktop.
Save gokulkrishh/9ff9c05300634088d8268d255f2783e1 to your computer and use it in GitHub Desktop.
CSS Layout - Align an element Horizontal & Vertical center
/* HTML */
<div class="container">
<div class="child"></div>
<div>
/* Basic Style */
.container {
width: 500px;
height: 500px;
background: #ccc;
}
.child {
background: red;
width: 100px;
height: 100px;
}
/* Different ways to make an element horizontal & vertical center */
/* Way 1 - Using position: absolute; */
.container {
position: relative;
}
.child {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
}
/* Way 2 - Using Flexbox */
.container {
display: flex;
align-items: center;
justify-content: center;
}
/* Way 3 - Using CSS Grid */
.container {
display: grid;
place-items: center;
}
/* Way 4 - Using position: absolute; transform */
.container {
position: relative;
}
.child {
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}
/* Way 5 - Using display: table & table-cell */
.container {
display: table;
}
.child {
background: red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
@gokulkrishh
Copy link
Author

gokulkrishh commented Jan 3, 2019

Preview for container & child (For all ways except way 5, because .child takes full height and width of the parent )

screenshot 2019-01-03 at 8 20 07 pm

@spselvaelancier
Copy link

Thank You its help me lot..

@gokulkrishh
Copy link
Author

@spselvaelancier Glad, it was helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment