montrealmike
montrealmike

Reputation: 11641

CSS float align at top

What is the best way (without js) to make all cells align (ie, have three cells per row in this case).

HTML

<ul id="list">
    <li>Line1 this is a very long line that will break the layout</li>
    <li>Line2</li>
    <li>Line3</li>
    <li>Line4 this is a very long line that will break the layout</li>
    <li>Line5</li>
    <li>Line6</li>
    <li>Line7 this is a very long line that will break the layout</li>
    <li>Line8</li>
    <li>Line9</li>
</ul>

CSS

#list li{
    float: left;
    width: 33%;
    border: 1px #000 solid;
}

Result

enter image description here

It can all be seen in this Fiddle.

The number of items per line may change (ie, I don't know where the new line will start), and the height of each is variable (ie, cannot force height).

Upvotes: 10

Views: 35319

Answers (6)

js1568
js1568

Reputation: 7032

You can use vertical-align to ensure that the text of the blocks are always at the top regardless of height.

#list li {
  display:inline-block;
  vertical-align:top;
}

https://css-tricks.com/almanac/properties/v/vertical-align/

Upvotes: 22

Crisman
Crisman

Reputation: 418

The flex-box solution:

#list {
  display: flex;
  flex-wrap: wrap; /*allows items to flow into a new row*/
}
#list li {
  width: 33%;
  border: 1px #000 solid;
}

results in:

enter image description here

demo: http://jsfiddle.net/xja40zod/2/

Upvotes: 0

js1568
js1568

Reputation: 7032

You need to use clear:left; on the first element of each new line.

With CSS3 you can do:

#list li:nth-of-type(3n+1) {
  clear:left;
}

http://reference.sitepoint.com/css/pseudoclass-nthoftype

Upvotes: 2

Joseph Marikle
Joseph Marikle

Reputation: 78560

#list li{
    display:inline-block;
    width: 30%;
    border: 1px #000 solid;
}

http://jsfiddle.net/NF7UY/

That's my solution

Upvotes: 0

Marc B
Marc B

Reputation: 360772

Add this to your css:

display: inline-block;
height: 3em; /* adjust to fit largest content in any of the blocks */

and reduce the width slightly - the 1px border is added to the width, so you're ending up with 100% + 6px, meaning only 2 blocks show up per line.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

I'm not sure this is what you mean, but they're aligned:

#list li{
    float: left;
    width: 33%;
    border: 1px #000 solid;
    min-height:40px;
}

Upvotes: 0

Related Questions