Last active
January 19, 2022 01:36
-
-
Save ayoubkhan558-zz/58f333ebcc3037957da0802796df4965 to your computer and use it in GitHub Desktop.
Methods to Center a Div in HTML CSS
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> | |
<head> | |
<title>Page Title</title> | |
<style> | |
body { | |
background: pink; | |
} | |
div.container { | |
height: 10em; | |
position: relative; | |
background: yellow; | |
} | |
div.container .content { | |
margin: 0; | |
background: gray; | |
padding: 15px; | |
text-transform: uppercase; | |
color: #fff; | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
transform: translate(-50%, -50%); | |
} | |
div.container2 { | |
height: 10em; | |
position: relative; | |
background: red; | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
} | |
div.container2 .content2 { | |
margin: 0; | |
background: gray; | |
padding: 15px; | |
text-transform: uppercase; | |
color: #fff; | |
} | |
.center { | |
width: 35px; | |
height: 35px; | |
position: relative; | |
top: 50%; | |
left: 50%; | |
transform: translate(-50%, -50%); | |
background: red; | |
} | |
.center2 { | |
width: 35px; | |
height: 35px; | |
display: block; | |
margin: 0 auto; | |
background: green; | |
} | |
section { | |
background: black; | |
color: white; | |
border-radius: 1em; | |
padding: 1em; | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
margin-right: -50%; | |
transform: translate(-50%, -50%) | |
} | |
</style> | |
</head> | |
<body> | |
<h3>Centering a Div</h3> | |
<small>Method 1</small> | |
<div class=center></div> | |
<small>Method 2</small> | |
<div class=center2></div> | |
<h3>Centering Content</h3> | |
<small>Method 1</small> | |
<div class=container> | |
<div class="content"> | |
Text Here | |
</div> | |
</div> | |
<small>Method 2</small> | |
<div class=container2> | |
<div class="content2"> | |
Content | |
</div> | |
</div> | |
<h3>Centering a Viewport</h3> | |
<section> | |
<h1>Nicely centered</h1> | |
<p>This text block is vertically centered. | |
<p>Horizontally, too, if the window is wide enough. | |
</section> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment