Search code examples
cssalignmentvertical-alignmenttext-align

CSS - Horizontally and vertically distribute divs


So I've got this header with three elements in them. What I want is basically this:

http://jsfiddle.net/zktbfmqo/2/

Only with vertically centered content in each of the divs as well. Is there an easy and clever way to do this without using absolutes etc? Vertical-align: middle doesn't seem to do much, but that property isn't always easy to work with either.

HTML:

<div id="container">
    <div class="box1">Text</div>
    <div class="box2">Text</div>
    <div class="box3">Text</div>
    <span class="stretch"></span>
</div>

CSS:

#container {
    border: 2px dashed #444;
    height: 125px;

    text-align: justify;
    -ms-text-justify: distribute-all-lines;
    text-justify: distribute-all-lines;

    min-width: 612px;
}

.box1, .box2, .box3 {
    width: 150px;
    height: 125px;
    vertical-align: middle;
    display: inline-block;
    *display: inline;
    zoom: 1;
    text-align: center;
}
.stretch {
    width: 100%;
    display: inline-block;
    font-size: 0;
    line-height: 0
}

Solution

  • First you can achieve the same result in a better way by using Flexbox.

    For vertical align text to the middle you can simply approach that by adding the line-height property and set it to the same exact height of the container div so in your case it would be 125px or if you used flexbox it can be done with align-items: center , and here is the final code:

    .wrapper {
    display: -webkit-flex;
    display: flex;
    
    -webkit-flex-flow: row nowrap; /* Safari 6.1+ */
    flex-flow: row nowrap;
    
    -webkit-justify-content: space-between; /* Safari 6.1+ */
    justify-content: space-between;
      
    font-weight: bold;
    
    height: 125px;
    min-width: 612px;
    padding: 5px;
    
    border: 2px dashed #444;
    }
    
    .wrapper > div{
    display: -webkit-flex;
    display: flex;
    -webkit-flex-basis: 150px;
    flex-basis: 150px;
    justify-content: center;
    align-items: center;
    
    }
    .aside-1, .aside-3{
    background: #ccc
    }
    .aside-2{
    background: #0ff;
    }
    <div class="wrapper">
       <div class="aside aside-1">text1</div>
       <div class="aside aside-2">text2</div>
       <div class="aside aside-3">text3</div>
    </div>