View All Posts

Vertical Align Methods

Vertical alignment can be a pain. Here are the methods that have worked well for me.

Transform Method

/* Vertical align - Transform
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.vcenter {
display: inline-block;
position: absolute;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
background: gold;
width: 100px;
height: 40px;
}

NOTE: Parent or grandparent element will need to be set to position:relative; for the transform method.


Flex Method

/* Vertical align - Flex
–––––––––––––––––––––––––––––––––––––––––––––––––– */

/*Container or Parent*/
.Aligner {
display: flex !important;
align-items: center;

}

/*items*/
.Aligner-item--center {
align-self: center;
}

.Aligner-item--top {
align-self: flex-start;
}

.Aligner-item--bottom {
align-self: flex-end;
}

 

<div class="Aligner"> 
<div class="Aligner-item Aligner-item--top">…</div> 
<div class="Aligner-item--center">…</div>
<div class="Aligner-item Aligner-item--bottom">…</div> 
</div>

Transform Method - SCSS Mixin

/* Vertical align - SCSS
–––––––––––––––––––––––––––––––––––––––––––––––––– */
@mixin centerer($horizontal: true, $vertical: true) {
position:absolute;
display: inline-block;
@if ($horizontal and $vertical) {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} @else if ($horizontal) {
left: 50%;
transform: translate(-50%, 0);
} @else if ($vertical) {
top: 50%;
transform: translate(0, -50%);
}
}

.container {
position:relative;
}

.box {
@include centerer(true,true);
}

Related Sources: http://vanseodesign.com/css/vertical-centering/https://css-tricks.com/centering-css-complete-guide/


  
  
  
  
Posted: June 29th, 2016
Updated: July 13th, 2016

Category: Snippets
Tags: , , ,