Tag Archives: css

6 methods to vertically align anything in pure CSS

6 methods to vertically align anything in pure CSS

This is a common problem with front-end web design. Browsers and CSS still need to work on easy vertical alignment. Having to use onload javascript and inline CSS for this matter is gross!

But there are pure CSS solutions, only not straight forward. The example HTML code for this is the following, where we want the children to be vertically centered in the parent element:

<div class="parent">
    <div class="children">I'm vertically centered!</div>
</div>

The translateY method

Already appointed by Chris Coyier back in 2013.

  1. We move the children element (it must be positioned either relative, absolute or fixed) down to the middle of it’s parent using top: 50%,
  2. then we pull it back up by half, with transform: translateY(-50%).

This works because the “top: 50%” is 50% of the parent’s height, while the “translateY: -50%” is -50% of the child’s height.

.children {
position: relative;
top: 50%;
transform: translateY(-50%);
}

Or using vendor prefixes this ends up as:

.children {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}

PROS: The biggest pro here is that you don’t need to specify the height of the element and it is clean CSS. Also, it works on floated elements.

CONS: It makes use of vendor prefixes. If you want to centralice a relative positioned element, its parent must have a height value, i.e., it won’t work if said parent’s height is set to auto. Also, this method can cause elements to be blurry due to the element being placed on a “half pixel”. A solution for this is to set its parent element to preserve-3d. Like following:

.parent {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}

Calc method

Another common way to achieve pixel perfect vertical alignment is using the calc property.
PROS: It is widely supported,
CONS: but has it’s drawbacks nevertheless, like having to specify a height for the element.

.children {
height: 250px;
margin-top: calc(50%-125px);
}

Tables and table-cell method

Some would argue that table/table-cell can resolve this issue.

.parent {
display: table-cell;
vertical-align: middle;
}

Although CSS does not have semantics and it will completely validate (PROS), some have problems using table properties (not tags, though) for non tabular data (CONS). This method could also incur in performance issues on CSS3 animations. Also, it does not work on floated elements.

Inline block method

PROS: This method works great to avoiding blurred pixels, and it doesn’t make use of vendor prefixes.
CONS: but it is far tricker and requires greater sintaxis than the other methods.


.parent {
  text-align: center;
  width: 200px;
  height: 200px;
}

.parent:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

.children {
  display: inline-block;
  width: 120px;
  height: 101px;
  vertical-align: middle;
}

Here’s a Codepen example:
http://codepen.io/lucasmotta/pen/hBcEw

Absolute positioning method

In this example we’re using img tags to create galleries. Having an HTML like:

<div class="parent">
      <img src="http://lorempixel.com/200/150/cats/1">
</div>

could be solved by:

.parent {
  width: 10%; /* 1 */
  position: relative; /* 1 */
  border: 1px solid silver;
}

/**
 * Making figure frame always squared 
 * Keeping 1:1 ratio with padding hack
 */
.parent:before {
  content: '';
  display: block;
  padding-top: 100%;
}

/**
 * Absolutely positioned image
 * 1. Sticking to side
 * 2. Absolutely centering 
 * 3. Fluid stuff
 */
img {
  position: absolute;
  top: 0; /* 1 */
  left: 0; /* 1 */
  right: 0; /* 1 */
  bottom: 0; /* 1 */
  margin: auto; /* 2 */
  max-width: 100%; /* 3 */
  height: auto; /* 3 */
}

And this methods extends to a gallery in list form by making the ul the parent and the li tags de children. Or even better, li tags being parent and figure tags being the children.

This Codepen example goes for it!
http://codepen.io/HugoGiraudel/pen/ucKEC

The Flexbox solution

From css-tricks:

The Flexbox Layout (Flexible Box) module (currently a W3C Last Call Working Draft) aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic (thus the word “flex”).

.parent{
display: flex;
align-items: center;
justify-content: center;
height: 300px; /* Or whatever */
}

.child {
  width: 100px;  /* Or whatever */
  height: 100px; /* Or whatever */
  margin: auto;  /* Magic! */
}

I haven’t tried this out myself, but looks like it is extremely easy. Also try out with justify-content: space-between to align left and right and distribute the white space among the middle elements.

This is an elaborate community curated list on github on bugs and workarounds of this flex stuff, but I’m guessing the spec will continune to evolve and vendors will adapt to this.


Well there, I hope to have put together some of the most common hacks to vertical alignment. Now, chose which one is better for you.

Active Screen Scrolling Mockup Effect for Websites

Active Screen Scrolling Mockup Effect for Websites

This is what I wanted to achieve for website portfolio pages like my last MONKEY Pictures item:

screenshot
*Scroll Me

And I wanted it to be responsive and to be super easily inserted into my WordPress editor. So, as we already did on the post on correct figure captioning on WordPress, we will be using again the function html5_insert_image to hook our own html5 code into WordPress.

MockUp image download

First, download the image from here and be sure to remember where your are uploading it.

functions.php

Then, copy & Paste the following code into your functions.php:

function html5_insert_image($html, $id, $caption, $title, $align, $url, $size, $alt) {
$url = wp_get_attachment_url($id);
$src = wp_get_attachment_image_src( $id, $size, false );

if ($caption) {
    if ($caption ="screenshot"){
        $html5 = "<div class='screendiv'><div class='dummy'></div><div class='screenpack'><figure class='screenshot' >";
        $html5 .= "<img src='$src[0]' alt='$alt' class='align$align'/>";
        $html5 .= "</figure><div class='screen-overlay'><span>*Scroll Me</span></div></div></div>";
    } else {
    $html5 = "<figure class='align$align withcaption' >";
    $html5 .= "<a href='$url' data-title='$caption'><img src='$src[0]' alt='$alt' class='align$align'/></a>";
    $html5 .= "<figcaption>$caption</figcaption>";
    $html5 .= "</figure>";
    }
} else {
    $html5 = "<figure class='align$align nocaption' >";
    $html5 .= "<a href='$url'><img src='$src[0]' alt='$alt' class='align$align'/></a>";
    $html5 .= "</figure>";
}

return $html5;
}
add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );

What this does is to insert a different code snippet depending on whether there is caption defined or not, and what this caption says. So now, whenever you upload a new image using the «Add Media» functionality and write «screenshot» as a caption, this is the html code that will be sent to the editor:

<div class='screendiv'><div class='dummy'></div><div class='screenpack'><figure class='screenshot' ><img src='$src[0]' alt='$alt' class='align$align'/></figure><div class='screen-overlay'><span>*Scroll Me</span></div></div></div>

css styling

Finally, for it to work nice you’ll need the following css rules on your style.css:

div.screendiv {
    display: inline-block;
    position: relative;
    width: 100%;
}
.dummy {
    margin-top: 100%;
}
.screenpack{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

figure.screenshot {
    position:absolute; 
    height:55%;
    z-index:100;
    top:3.5%;
    width:96.5%;
    overflow-y:scroll;
    margin-left:3.5%;
}
.screen-overlay {
    position:absolute; 
    z-index: 10000000;
    background: url('url-to-mockup.png') no-repeat; 
    background-size: contain;
    width:100%;
    height:100%;
    pointer-events:none;
}
figure.screenshot img {margin:0; padding:0;}
.screen-overlay span{color: #fff; font-size: 0.75em; float: right; margin-top:0.5%; margin-right: 3%; font-style: italic; text-transform: uppercase;}

Inline css (not usually a good idea)

Although it is not usually a good idea to inline you css, when it comes to sporadic use of a few snippets I do like to make use of this instead of cluttering my css files. So, to avoid the css avoid, the new code for the functions.php would be:

unction html5_insert_image($html, $id, $caption, $title, $align, $url, $size, $alt) {
$url = wp_get_attachment_url($id);
$src = wp_get_attachment_image_src( $id, $size, false );

if ($caption) {
    if ($caption ="screenshot"){
        $html5 = "<div class='screendiv' style='display: inline-block; position: relative; width: 100%;'><div class='dummy' style='margin-top: 100%;'></div><div class='screenpack' style='position: absolute; top: 0; bottom: 0; left: 0; right: 0;'><figure class='screenshot' style='position:absolute; height:55%; z-index:10; top:3.5%; width:96.5%; overflow-y:scroll; margin-left:3.5%;'><img src='$src[0]' alt='$alt' class='align$align' style='margin:0 !important; padding:0 !important;'/></figure><div class='screen-overlay' style='position:absolute;z-index: 100; background: url(http://obsessive-coffee-disorder.com/wp-content/themes/implicit-child/images/imac-transp.png) no-repeat; background-size: contain; width:100%; height:100%; pointer-events:none;'><span style='color: #fff; font-size: 0.75em; float: right; margin-top:0.5%; margin-right: 3%; font-style: italic; text-transform: uppercase;'>*Scroll Me</span></div></div></div>";
    } else {
    $html5 = "<figure class='align$align withcaption' >";
    $html5 .= "<a href='$url' data-title='$caption'><img src='$src[0]' alt='$alt' class='align$align'/></a>";
    $html5 .= "<figcaption>$caption</figcaption>";
    $html5 .= "</figure>";
    }
} else {
    $html5 = "<figure class='align$align nocaption' >";
    $html5 .= "<a href='$url'><img src='$src[0]' alt='$alt' class='align$align'/></a>";
    $html5 .= "</figure>";
}

return $html5;
}
add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );

How does it work?

Well, the structure is pretty simple. Two elements, figure and div with overlay picture wrapped by the same div. This is then wrapped inside another div together with a dummy content div that is need to help calculate the height of the figure and the overlay for any width and, thus, making the mockup totally responsive for any screen width! And without any javascript or media-queries!

Untitled-1

The problem

Setting the width to 100% (or whatever you want it to be) of both —figure and screen-overlay— is easy, but the height isn’t as it depends entirely on the ratio and proportions of your overlay image. Using the css3 “function” calc() for a ration calculation on the height wasn’t going to help because the percentage used is taken from the height of the parent div, not it’s width.

So can you have a div with a height that is always the same as (or proportional to) it’s width?

I found the answer here: JSFIDDLE, and by changing the dummy’s percentage you can actually decide on your own div’s ratio. Clever, right?

Ultimately

  1. Download the overlay mockup image or create one yourself.
  2. Copy & paste the functions.php code into your functions file
  3. Copy & paste the css into the style.css file
  4. Change as desired
  5. Add an image and write «screenshot» as it’s caption
  6. Repeat 5 as many times as desired