Search code examples
htmlcssalignmentvertical-alignment

How to prevent nested elements from wrapping without specifying widths


I'm having trouble keeping two nested inline-blocks aligned without specifying widths. I can get the behavior I want using tables but would prefer to use simpler markup. Here's the basic markup:

<div class="error">
  <i></i>
  <div class="message">Ruh oh</div>
</div>

Here is the basic css:

.error {
    border: 2px solid red;
    padding: 8px 10px;
}

i {
    display: inline-block;
    width: 45px;
    vertical-align: middle;
}

.message {
    display: inline-block;
    vertical-align: middle;
}

Here are the requirements:

  • .error can be any width (usually 100%)
  • i will be fixed width (usually 45px)
  • .message will fill the remaining width of the parent .error
  • both i and .message will be vertically aligned in the middle
  • .message cannot wrap under i
  • no javascript

Here is a fiddle showing a good line (short error), a bad line (longer error messages wrap below the i) and a working example with tables (but I don't want tables). Please enlighten me!

http://jsfiddle.net/3m2db1hw/


Solution

  • you need to use display:table to parent Div and display:table-cell to children i.e. <i> and <div>

    .error {
        border: 2px solid red;
        padding: 8px 10px;
        display:table;
    }
    
    i {
        width: 45px;
        vertical-align: middle;
        display:table-cell !important;
    }
    
    .message {
        display: table-cell;
        vertical-align: middle;
    }
    

    here is edited jsfiddle http://jsfiddle.net/3m2db1hw/1/