GRowing
GRowing

Reputation: 4727

CSS - floating elements lose alignment

I hope someone can explain this to me and offer a solution..

I created a fiddle to demonstrate the issue and to explain the question

http://jsfiddle.net/s6ow1oq3/

Here is the question..

When elements such as <li> or <div> are floated left and they are set to a particular width but they don't/can't have a fixed height,,, how can I insure that element that breaks into new row gets aligned to the beginning of the next row?

In the fiddle example the second example demonstrates the issue while the first one is desired.

Here is the fiddle code too:

CSS:

li {
    list-style:    none;
}

#one li, #two li {
    width:    22%;
    float:    left;
    margin:   7px;
    padding:  7px;
    border:1px solid #DDD;
}

.clearfix {
    clear:    both;
    float:    none;
}

HTML:

<!-- Unordered List Examples -->

<div id="one">
<ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
    <li>f</li>
    <li>g</li>
    <li>h</li>
</ul>
<div class="clearfix">
</div>

<hr/>

<div id="two">
<ul>
    <li>a</li>
    <li>b</li>
    <li>c1<br/>c2<br/>c3<br/>c4</li>
    <li>d</li>
    <li>e</li>
    <li>f</li>
    <li>g</li>
    <li>h</li>
</ul>
<div class="clearfix">
</div>

Upvotes: 0

Views: 96

Answers (2)

Ryan Wheale
Ryan Wheale

Reputation: 28440

Use display: inline-block; - the most under-appreciated display type IMO.

The main thing you can't do is have 100% width coverage, but since your example doesn't require the items to butt up against one another, it's a perfect use case for inline-block

The trick is to make sure that all of your width's and margins add up to roughly 99% instead of 100%.

http://jsfiddle.net/ryanwheale/s6ow1oq3/3/

#one li, #two li {
    display: inline-block;
    vertical-align: top;
    width:    22%;
    margin:   1.2%;
    padding:  7px;
    border:1px solid #DDD;
}

Upvotes: 1

Christian
Christian

Reputation: 19750

Assuming it's always 4 columns, you could use li:nth-child(4n + 1) to clear the first element on every row. For example:

li:nth-child(4n + 1) {
    clear: both;
}

jsFiddle: http://jsfiddle.net/s6ow1oq3/2/

Upvotes: 2

Related Questions