Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center float boxes horizontally

I want to display some floating boxes (divs containing thumbnails) and the number of thumbnails depends on the current page width. For example:

<div class="container">
  <div class="box1" style="float:left;width:120px;height:120px;margin-right:10px;">Thumbnail image here</div>
  <div class="box2" style="float:left;width:120px;height:120px;margin-right:10px;">Thumbnail image here</div>
  <div class="box3" style="float:left;width:120px;height:120px;margin-right:10px;">Thumbnail image here</div>
  <div class="box4" style="float:left;width:120px;height:120px;margin-right:10px;">Thumbnail image here</div>
    .......... ETC
</div>

the problem is that for a given width it shows for example 4 boxes on each row, but they are all left aligned and there is some white space to the right, how can i center horizontally for each row??

Something like this: http://realworldstyle.com/thumbs_3.html but with boxes centered horizontally on the page...

thanks in advance,

like image 481
fidoboy Avatar asked Jun 24 '26 23:06

fidoboy


2 Answers

I think the only way to get the elements centered is to work not with float, but setting the images display: inline. That way, you can align them at will using the parent container's text-align property.

But that will give you additional issues with vertical margins and setting height. But as far as I know, it's the only reliable cross-browser way as long as inline-block is not widely supported.

like image 135
Pekka Avatar answered Jun 27 '26 13:06

Pekka


Sorry, but will not be able to do what you are wanting with straight CSS + HTML. (Take a look at @Pekka for an alternative, though if the row of thumbnails don't fill the whole row, they would be centered by themselves on the last row)

You would need to have a fixed width on the parent object .container with margin-left: auto and margin-right:auto which you cannot do since it is a fluid width page.

Here is how I would go about doing it, though it is sure to have some bugs you will need to work around:

  1. Bind a javascript event to the window.resize event
  2. Get the new document width and see how many thumbnails would fit on one row
  3. Set the width of the div.container to be that width plus the little bit of margin on the right. This div would always have a margin-left and margin-right of auto

This will center the thumbnails as best as possible. Depending on your visual display, you may need an additional wrapping div to provide the 100% width background.

like image 20
Doug Neiner Avatar answered Jun 27 '26 14:06

Doug Neiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!