Search code examples
csscentervertical-alignmentcentering

Vertical centering unknown height


I'm trying to vertically center an image in a DIV that doesn't have a fixed/specified height. I've tried building on the Centering in the unknown article on CSS Tricks but for that to work you need to specify the height. Rather deceiving article title.

Here's my JS Fiddle: http://jsfiddle.net/6J2WA/

This is what I'd like (picture): http://cl.ly/image/1k0h262c2c3s

CSS

/* This parent can be any width and height */
.block {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
   height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
}


.inner {
max-width: 960px;
margin: 0 auto;
overflow: hidden;
    background: #ef4;
}

.c-3 {  
width: 29.3%;
float: left;
margin-left: 6%;
    background: #e4f;
}

#you-and-us .c-3 { width: 33.5%; }
#you-and-us .c-3:first-child { text-align: right; margin: 0; }
#you-and-us .c-3:nth-child(2) { width: 21%; text-align: center; position: relative; }

Solution

  • The reason you can't use the pseudo element technique is because you don't have enough ancestor elements that are 100% of the height of the #you-and-us element.

    You can simplify the whole thing if you throw out floats and use display: table-cell for your .c-3 elements.

    http://jsfiddle.net/6J2WA/5/

    /* This parent can be any width and height */
    .block {
        text-align: center;
    }
    
    .inner {
        max-width: 960px;
        margin: 0 auto;
        overflow: hidden;
        background: #ef4;
    }
    
    .c-3 {  
        display: table-cell;
        background: #e4f;
    }
    
    #you-and-us .c-3 { width: 33.5%; }
    #you-and-us .c-3:first-child { text-align: right; }
    #you-and-us .c-3:nth-child(2) { width: 21%; text-align: center; position: relative; background: yellow; vertical-align: middle; }