Stop floating divs from wrapping

Nicholas picture Nicholas · Apr 11, 2011 · Viewed 114.5k times · Source

I want to have a row of divs (cells) that don't wrap if the browser is too narrow to fit them.

I've searched Stack, and couldn't find a working answer to what I think should be a simple css question.

The cells have specified width. However I don't want to specify the width of the row, the width should automatically be the width of its child cells.

If the viewport is too narrow to accomodate the rows, then the div should overflow with scrollbars.

Please provide your answer as working code snippet, as I've tried a lot of the solutions I've seen elsewhere (like specify width: 100% and they don't seem to work).

I'm looking for a HTML/CSS only solution, no JavaScript.

At the moment I'm actually hard coding the width of the row to a really big number.

Answer

Calvin picture Calvin · Jun 13, 2012

The CSS property display: inline-block was designed to address this need. You can read a bit about it here: http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

Below is an example of its use. The key elements are that the row element has white-space: nowrap and the cell elements have display: inline-block. This example should work on most major browsers; a compatibility table is available here: http://caniuse.com/#feat=inline-block

<html>
<body>
<style>

.row {
    float:left;
    border: 1px solid yellow;
    width: 100%;
    overflow: auto;
    white-space: nowrap;
}

.cell {
    display: inline-block;
    border: 1px solid red;
    width: 200px;
    height: 100px;
}
</style>

<div class="row">
    <div class="cell">a</div>
    <div class="cell">b</div>
    <div class="cell">c</div>
</div>


</body>
</html>