Karel Bílek
Karel Bílek

Reputation: 37694

How to make more divs after each other non-wrapping, but the entire list wrapping?

I have divs after each other that look like this.

<div class="tag">one tag</div>
<div class="tag">second tag</div>
<div class="tag">third tag</div>
...50 more of them....


(in CSS)

.tag {
    display:inline
}

I found out that I have too many of them and they start breaking in the middle, and I don't want that.

However, when I set the nowrap like this

.tag {
    display:inline;
    white-space:nowrap;
}

all of them are on one line, making more than 100% of the window. I don't want that.

What I want: if there are too many of these divs on one line, the list of the divs can break, but the divs themselves don't. I just don't want to break the divs in the middle.

I hope I tell it clearly enough.

Upvotes: 1

Views: 81

Answers (3)

andyb
andyb

Reputation: 43823

Depending on the browsers you need/want to support, you may find using

.tag {
    display:inline-block;
    vertical-align:top;
}

a better solution. Since it is a <div> that you want to apply this to, the style will not work out of the box for IE5-7 - see http://www.quirksmode.org/css/display.html#t03. There are workarounds of course - How to fix display:inline-block on IE6? - if you want to use it with those browsers.

The benefit of inline-block is that you do not need to clear the floated content and also that your elements are not rendered out of normal flow. I try to avoid floating elements where possible as in my experience it has caused layout problems.

However, there are a couple of potential catches with this approach. One of which I have already addressed, by adding a vertical-align:top rule. See a previous answer for why this happens - https://stackoverflow.com/a/12950536/637889

The other is due to potentially unwanted white-space between the inline-block elements. See http://css-tricks.com/fighting-the-space-between-inline-block-elements/ for some clever ways around this.

Upvotes: 0

J&#248;rgen R
J&#248;rgen R

Reputation: 10806

If I understand right, you want them to lay side to side, and then break to a new line when the row is full, but not in the middle of a div.

All you need is

.tag {
    float: left;
}

See fiddle here for demo.

You can also add padding-left: 5px; if you want some space between them.

Upvotes: 1

Karel B&#237;lek
Karel B&#237;lek

Reputation: 37694

.tag {
    display:inline;
    white-space:nowrap;
    float:left;
}

That worked. (and adding "clearing" empty div with clear:both under that.)

Upvotes: 0

Related Questions