How to force inline divs to stay on same line?

Here’s one method using inline-block for the left and middle and position:absolute for the right element.

Example

jsFiddle

HTML

<div id="parent" style="width:100%">
    <div id="colLeft">left</div><!--
    --><div id="colCenter">Some really long text in the center. Some really long text in the center.</div>
    <div id="colRight">right</div>
</div>

CSS

html, body {
    margin: 0px;
    padding: 0px;
}
#parent {
    background-color: #eee;
    height: 48px;
    position:relative;
    overflow:hidden;
    white-space: nowrap;
}
#colLeft {
    background-color: #ff8b8b;
    height: 48px;
    display: inline-block;
}
#colCenter {
    background-color: orange;
    height: 48px;
    display: inline-block;
    overflow: hidden;
}
#colRight {
    background-color: #c3d0ff;
    height: 48px;
    display: inline;
    float: right;
    position:absolute;
    top:0;
    right:0;
}

Since it relys on inline-block, there is a comment in between the <div>s to get rid of the spacing illustrated in this image:

Ugly spacing

text-overflow:ellipsis

To achieve this when using text-overflow:ellipsis you may need to fallback on JavaScript, here is a possible solution (jsFiddle).

Ellipsis using JavaScript

window.onresize = updateDimensions;

function updateDimensions() {
    var parent = document.getElementById('parent');
    var left = document.getElementById('colLeft');
    var right = document.getElementById('colRight');
    var middle = document.getElementById('colCenter');

    middle.style.width = (parent.offsetWidth - right.offsetWidth - left.offsetWidth)  + 'px';
}

Leave a Comment