6

I have a container (image gallery) that is max-width:80%. Inside, images are floated left forming columns and rows. As you shrink/expand the browser window, more or fewer images fit into each row and there is typically a "remainder" at the end of each row, when there is not enough space to fit another full image:

http://jsfiddle.net/vladmalik/DRLXE/1/

I'd like the container to expand or contract to exactly hug however many floats fit into a column (so there is never a yellow remainder to the right). Can this be done with CSS?

HTML:

<section>  
   <div></div>  
   <div></div>  
   <div></div>  
   <div></div>  
   <div></div>  
</section>  

CSS:

div {  
   width: 100px;  
   height: 100px;  
   float:left;  
   background: red;  
}  

section {  
   margin: 0 auto;  
   max-width: 80%;  
   background:yellow;  
   overflow: hidden;  
}  
Vlad
  • 612
  • 1
  • 7
  • 13
  • +1 for good question. At first I thought, sure, just float the outer container too. But that won't work. Stand by. – Mr Lister Feb 01 '13 at 15:11

2 Answers2

0

It can't be done purely in CSS (especially if it has to be cross-browser compatibile), the best you can do is to set divs width in percent and then set their css backgrounds like there:

div {
    width:25%;
    height: 100px;
    float:left;
    background: transparent url('http://1.bp.blogspot.com/_muMRp22Klwo/SuGeqr4TeII/AAAAAAAAAVY/afpIYqkyPkM/s400/sad-dog.jpg') center center no-repeat;
}

http://jsfiddle.net/DRLXE/3/

Still far from perfection though.

Bart Karp
  • 649
  • 3
  • 7
0

I'm thinking you might be able to do this with a jQuery .length() of div that constantly re-calculates the needed width and height based on window size. So if...

div {
  width: 100px;
  height: 100px;
  float: left;
} 

Then...

$(document).ready(function(){
    changeSize();
});

function changeSize(){
    var length = $('div').length(); //let's say is 12 

    var windowwidth = $(window).width(); //let's say it's 1000px, 

    if (length >= 10 && windowwidth >= 600px){ 
        $('section').css('width', '300px'); 
        $('section').css('min-height', '400px'); 
    }
    else if {
        //Some more sizing code...
    }
}

$(window).resize(function() {
    changeSize();
});

You would need to set the conditions in the if statements based on your needs, but this method should do it.

Plummer
  • 6,522
  • 13
  • 47
  • 75
  • That's what I figured. I thought maybe there was some CSS quirk I could use. Thanks. – Vlad Feb 02 '13 at 15:57