Created
July 20, 2022 11:27
-
-
Save Inayatullahsh/304dab93956304da624ecccc3789784f to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>3 ways to center a div</title> | |
<style> | |
body { | |
font-family: sans-serif; | |
} | |
.wrapper { | |
height: 100vh; | |
} | |
.wrapper > .item { | |
padding: 5rem 5rem; | |
color: #f5f5f5; | |
font-weight: bold; | |
} | |
/* | |
Three ways to center a div in pure CSS: | |
1) Center div using CSS Flexbox | |
Tutorial link: | |
https://css-tricks.com/snippets/css/a-guide-to-flexbox/ | |
*/ | |
.flexbox { | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
} | |
.flexbox > .item { | |
background-color: #16a34a; | |
} | |
/* | |
2) Center div using CSS Grid | |
Tutorial link: | |
https://css-tricks.com/snippets/css/complete-guide-grid/ | |
*/ | |
.grid { | |
display: grid; | |
place-items: center; | |
} | |
.grid > .item { | |
background-color: #0284c7; | |
} | |
/* | |
3) Center div using CSS transform property | |
Tutorial link: | |
https://www.w3schools.com/css/css3_2dtransforms.asp | |
*/ | |
.translate { | |
position: relative; | |
} | |
.translate > .item { | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
transform: translate(-50%, -50%); | |
background-color: #eab308; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="wrapper flexbox"> | |
<div class="item"> | |
Flexbox | |
</div> | |
</div> | |
<div class="wrapper grid"> | |
<div class="item"> | |
Grid | |
</div> | |
</div> | |
<div class="wrapper translate"> | |
<div class="item"> | |
Transform | |
</div> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment