Aahan
Aahan

Reputation: 21

How to prevent other elements from aligning right when one element is floated left?

[EDIT] Thanks to herkulano and GerManson whose fixes worked for me.

But I am unable to decide which is better, reliable and cross-browser compatible? "overflow" or "clearfix:? Please help me with this, and I am good to go.


If my question is not clear, it will be, now. Just read on please...

(I am trying to display some thumbnails in php and these are the respective codes I am using.)

1. The following is the CSS code that I am using:

#gallerythumbnailsx { margin: 10px; }
#gallerythumbnailsx .gallery-item { float: left; margin-top: 10px; text-align: center; }
#gallerythumbnailsx img { border: 2px solid #cfcfcf; margin-left: 5px; }
#gallerythumbnailsx .gallery-caption { margin-left: 0; }

2. related php code used is:

<div id="gallerythumbnailsx"><?php echo show_all_thumbs(); ?></div>
<p>Aahan is great!</p>

3. This is how the resultant HTML is displayed:

<div id="gallerythumbnailsx">
    <dl class="gallery-item">
        <dt class="gallery-icon">
            <a href="http://example.com/"><img width="100" height="75" src="http://example.com/xxx.jpg"></a>
        </dt>
    </dl>

    <dl class="gallery-item">
        <dt class="gallery-icon">
            <a href="http://example.com/"><img width="100" height="75" src="http://example.com/xxx1.jpg"></a>
        </dt>
    </dl>

    <dl class="gallery-item">
        <dt class="gallery-icon">
            <a href="http://example.com/"><img width="100" height="75" src="http://example.com/xxx3.jpg"></a>
        </dt>
    </dl>
</div>

Unfortunately this is how it is being displayed (screenshot). The issue as you can see, is that the text "Aahan is great!" is being pushed to the right of the thumbnails since I use float: left for thumbnails in the CSS. I want the text in a new line.

Upvotes: 2

Views: 183

Answers (3)

herkulano
herkulano

Reputation: 558

Another way is to use the clearfix method on #gallerythumbnailsx it is cross-browser and this way you can reuse it elsewhere, just add the clearfix class where you use floats.

I made a working example: http://jsfiddle.net/XhRk6/

The .clearfix util class was taken from: http://html5boilerplate.com/

Upvotes: 1

Ben
Ben

Reputation: 13615

add p{clear:left;} to your CSS

awesome article explaining all floats

Added a JSFiddle for you

This uses the existing CSS (well it ignores the #gallerythumbnailsx .gallery-caption { margin-left: 0; } and #gallerythumbnailsx .gallery-item { float: left; margin-top: 10px; text-align: center; } since I don't see why you would need em.

Upvotes: 2

This will fix it, hopefully

#gallerythumbnailsx { margin: 10px; overflow: auto; }

Upvotes: 1

Related Questions