Revision - Vertical Centring
by andfinally
HTML
<section class="container flexbox">
<p class="inner">I'm vertically centred with flexbox.</p>
</section>
<section class="container stretch">
<p class="inner">I'm vertically centred with absolute positioning!</p>
</section>
<section class="container translateY">
<p class="inner">I'm vertically centred with translateY!</p>
</section>
<section class="container tableCell">
<p class="inner">I'm vertically centred with display:table-cell!</p>
</section>
<section class="container lineHeight">I'm vertically centered with line height!</section>
SCSS
.container {
height: 200px;
width: 600px;
margin-bottom: 20px;
background: #ddd;
}
.inner {
width: 80%;
margin: 0 auto;
padding: 1em 2em;
background: #E74C3C;
}
/* Flexbox. Margin auto in flex container absorbs extra space. */
.flexbox {
display: flex;
.inner {
width: 120px;
height: 100px;
margin: auto;
}
}
/* Stretch. Element must have a height. */
.stretch {
&.container {
position: relative;
}
.inner {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 25%;
width: 25%;
margin: auto;
}
}
/* Transform translateY. Parent must have height. You have to add transform-style to container to avoid
occasional blurred pixels. But that's not supported on older IE. */
.translateY {
&.container {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.inner {
position: relative;
top: 50%;
transform: translateY(-50%);
}
}
/* Table cell and vertical align */
.tableCell {
&.container {
display: table;
}
.inner {
display: table-cell;
vertical-align: middle;
}
}
/* Line height */
.lineHeight {
line-height: 200px;
}