Created
October 22, 2021 01:54
-
-
Save olitreadwell/fcdefe394137385038b411b443dc220f to your computer and use it in GitHub Desktop.
css horizontally and vertically center
This file contains 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
/* | |
======================================================================================= | |
Using negative margins equal to half of that width and height, | |
after you've absolutely positioned it at 50% / 50% will center | |
it with great cross browser support. | |
====================================================================================== | |
*/ | |
.parent { | |
position: relative; | |
} | |
.child { | |
width: 300px; | |
height: 100px; | |
padding: 20px; | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
margin: -70px 0 0 -170px; | |
} | |
/* | |
======================================================================================= | |
If you don't know the width or height, | |
you can use the transform property and a negative translate of 50% in both directions | |
(it is based on the current width/height of the element) to center. | |
======================================================================================= | |
*/ | |
.parent { | |
position: relative; | |
} | |
.child { | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
transform: translate(-50%, -50%); | |
} | |
/* | |
======================================================================================= | |
To center in both directions with flexbox, you need to use two centering properties: | |
======================================================================================= | |
*/ | |
.parent { | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment