Blog

the writings of

Vertical Alignment with CSS

August 8, 2014

Great technique for vertical aligning things using CSS3. Works for horizontal alignment too.

Read Original Source

Vertical alignment with CSS - was it an oversight? Or a conspiracy to waste a lot of designer and developer time?

At any rate, the linked article has a great technique for handling vertical alignment as far back as IE9.

Here's the upshot:


.vertical-align{
    position:relative; /* or absolute */
    top:50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

Alignment for Absolute Positioned Elements

Turns out this is a great way to vertically align or horizontally align absolutely positioned elements too. Normally, even horizontal alignment for absolutely positioned elements isn't easy unless you know the exact width of the element.

Here's the code:


/* Vertical Alignment */
.vertical-align{
    position: absolute;
    top:50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

/* Horizontal Alignment */
.horizontal-align{
    position: absolute;
    left:50%;
    -webkit-transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -o-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    transform: translateX(-50%);
}

Very useful - thanks for the tip!

Original Article: Vertical align anything with just 3 lines of CSS

blog comments powered by Disqus