收录日期:2020/10/25 06:43:56 时间:2010-09-07 02:54:23 标签:html,css

I have a gallery of images, each of which have the same width and height, say 10px. I want them spaced so that there are 5 on a row and they are each 5px apart, on all sides. The container div has 5px padding. There are multiple rows!

My problem is that if I give each image a left margin of 5px then either:

a) The container div is sized to fit and so only 4 images fit on a row as the fifths margin shunts it onto the next line.

b) The container div is sized with an extra 5px resulting in the an extra gap at the end of each row.

How should I style my images so they all fit on the correct row and without any ugly gaps without changing the containers padding?

You want to have right and bottom margin on the image divs and top, left padding on the container div.

CSS:

.container {
    padding: 5px 0 0 5px;
    background-color: green;
    width: 75px;
    position: relative;
    overflow: hidden;
}

.image {
    margin-right: 5px;
    margin-bottom: 5px;
    float:left;
    width:10px;
    height:10px;
    background-color: red;
}

HTML:

<div class="container">
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
</div>​

Check it out in action: http://jsfiddle.net/RP9Cg/

I just re-read your question again, and i saw the "without changing container's padding" bit. If you absolutely MUST have 5px padding on all sides of the container (not sure why, maybe you can say), you will need some extra styles for you images that are last in each row and all images in the last row of the gallery. Check out a possible solution: http://jsfiddle.net/T3HrJ/

I'm still pretty new to html & css myself, although when I wanted to do this I included

        text-align:center;

in the css file for that div, and that seemed to work. Worth a try!

In whatever code loop you are using to generate the image markup, you can use a modulo operator to assign a column-indexed CSS class to each image. Then in your styles you can do something like turn off the left margin on every image in the first "column".

Pseudo-code for loop output:

for ( $i=0; $i<gallerySize; $i++ ) {
    echo '<img class="galleryimage gridcolumn' . ($i%5) . '" src="blahblah.gif">';
}

Then you can use a CSS rule like this to change the first item in each row:

img.galleryimage { margin: 5px; }
img.gridcolumn0 { margin-left: 0px; }