Absolute Centering an Element
Different methods to absolutely center an element not only horizontally but also vertically within a container.
by Dini Mer
HTML
<div class="experiment experiment-1">
<p class="title">Absolute Centering:</p>
<div class="container">
<div class="centered-element">
<img src="//placekitten.com/210/210" alt="" />
</div>
</div>
</div><!--
--><div class="experiment experiment-2">
<p class="title">Table / Table-Cell:</p>
<div class="container-table">
<div class="container-table-cell">
<div class="centered-element">
<img src="//placeape.com/220/220" alt="" />
</div>
</div>
</div>
</div><!--
--><div class="experiment experiment-3">
<p class="title">Negative Margin:</p>
<div class="container">
<div class="centered-element">
<img src="//placebear.com/230/230" alt="" />
</div>
</div>
</div><!--
CSS
@import url(http://fonts.googleapis.com/css?family=Lato:400,700italic);
body { font-family: 'Lato', sans-serif; letter-spacing: 1px; }
*, *:before, *:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
overflow: hidden;
}
img {
display: block;
width: 100%;
height: auto;
}
.experiment {
display: inline-block;
position: relative;
height: 100%;
width: 33.3%;
background-color: #ddd;
border: 1px solid #888;
}
.experiment .title {
position: absolute;
top: 0;
left: 0;
display: inline-block;
padding: 8px;
z-index: 1;
}
.experiment .centered-element {
background: #506080;
padding: 10px;
max-width: 120px;
max-height: 120px;
}
/*
** Experiment 1: Absolute Centering:
*/
.experiment-1 .container {
position: relative;
width: 100%;
height: 100%;
}
.experiment-1 .centered-element {
position: absolute;
margin: auto;
top: 0; left: 0; bottom: 0; right: 0;
overflow: auto;
}
/*
** Experiment 2: Table / Table-Cell:
*/
.experiment-2 .container-table {
display: table;
width: 100%;
height: 100%;
}
.experiment-2 .container-table-cell {
display: table-cell;
vertical-align: middle;
}
.experiment-2 .centered-element {
margin: 0 auto;
}
/*
** Experiment 3: Negative Margin:
*/
.experiment-3 .container {
position: relative;
width: 100%;
height: 100%;
}
.experiment-3 .centered-element {
position: absolute;
width: 120px;
height: 120px;
top: 50%;
left: 50%;
margin-left: -60px; /* (width)/2 */
margin-top: -60px; /* (height)/2 */
}
JavaScript
/**
Source: http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/
**/