Skip to content

Instantly share code, notes, and snippets.

@oanhnn
Last active August 29, 2015 14:22
Show Gist options
  • Save oanhnn/9f0d8edb7d9e0c752f18 to your computer and use it in GitHub Desktop.
Save oanhnn/9f0d8edb7d9e0c752f18 to your computer and use it in GitHub Desktop.
CSS center block
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.container-block {
display: block;
position: relative;
background: #ccc; /* For visualization */
width: 500px; /* Changeable */
height: 500px; /* Changeable */
}
.center-block {
display: inline-block;
position: absolute;
left: 50%;
top:50%;
background: #009fe8; /* For visualization */
width: 320px; /* Fix width */
height: 250px; /* Fix height */
margin-left: -160px; /* -Width/2 */
margin-top: -125px; /* -Height/2 */
}
</style>
</head>
<body>
<div class="container-block">
<div class="center-block">
Content of center block 320x250
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.container-block {
display: table;
background: #ccc; /* For visualization */
}
.center-block {
display: table-cell;
text-align: center;
vertical-align: middle;
background: #009fe8; /* For visualization */
}
</style>
</head>
<body>
<table style="width: 100%; background: #ccc">
<tr>
<td style="text-align: center; vertical-align: middle; background: #009fe8">
Unknown stuff to be centered.
</td>
</tr>
</table>
<div class="container-block">
<div class="center-block">
Unknown stuff to be centered.
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
/* This parent can be any width and height */
.container-block {
text-align: center;
/* May want to do this if there is risk the container may be narrower than the element inside */
white-space: nowrap;
background: #ccc; /* For visualization */
width: 100%;
height: 500px;
}
/* The ghost, nudged to maintain perfect centering */
.container-block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
background: #eea236; /* For visualization */
}
/* The element to be centered, can also be of any width and height */
.center-block {
display: inline-block;
vertical-align: middle;
background: #009fe8; /* For visualization */
width: 300px;
}
</style>
</head>
<body>
<div class="container-block">
<div class="center-block">
Unknown stuff to be centered.
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment