Have you ever encountered wasting a bit of time trying to vertically-align items?
Well, now you shouldn’t, here are few CSS tips to center your elements vertically:
Using Fixed Padding
Element
HTML
<div class="center-vertically">
<span>Element</span>
</div>
CSS
<style>
.center-vertically { padding: 100px 0; text-align:center; }
.center-vertically span { padding:0px; margin:0px; line-height:1; }
</style>
Using Absolute Positioning
Element
HTML
<div class="center-vertically">
<span>Element</span>
</div>
CSS
<style>
.center-vertically { position: relative; height:200px; }
.center-vertically span { position: absolute; top: 50%; -ms-transform: translateY(-50%); transform: translateY(-50%); left: 0; right: 0; margin: 0 auto; display: block; }
</style>
Using Flexbox
Element
HTML
<div class="center-vertically">
<span>Element</span>
</div>
There are 2 ways to implement this:
1st
<style>
.center-vertically { display:flex; height:200px; align-items: center; }
.center-vertically span { flex-auto; }
</style>
2nd
<style>
.center-vertically { display:flex; height:200px; }
.center-vertically span { flex-auto; align-self: center; }
</style>
I love using flexbox, but there seems to be issues with IE10, although you can use these vendor prefixes:
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
I will also discuss fallback techniques for flexbox in another post.
Using Table
Element
HTML
<div class="center-vertically">
<div>
<span>Element</span>
</div>
</div>
CSS
<style>
.center-vertically { display: table; }
.center-vertically > div { display: table-cell; height: 200px; vertical-align: middle; text-align:center; }
.center-vertically > div span { padding:0px; margin:0px; line-height:1; }
</style>