Skip to content

Instantly share code, notes, and snippets.

@ayoubkhan558-zz
Last active January 19, 2022 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ayoubkhan558-zz/58f333ebcc3037957da0802796df4965 to your computer and use it in GitHub Desktop.
Save ayoubkhan558-zz/58f333ebcc3037957da0802796df4965 to your computer and use it in GitHub Desktop.
Methods to Center a Div in HTML CSS
<!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