Last active
February 7, 2022 15:08
-
-
Save gokulkrishh/9ff9c05300634088d8268d255f2783e1 to your computer and use it in GitHub Desktop.
CSS Layout - Align an element Horizontal & Vertical center
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Preview for container & child (For all ways except way 5, because
.child
takes full height and width of the parent )