Home Ask Login Register

Developers Planet

Your answer is one click away!

Jared February 2016

CSS: First row of image gallery coming out diagonal?

I have an array of images in php that I am trying to display as a gallery. It is working pretty well, except that the first row of the gallery comes out diagonal, with each image slightly below the one before it.

Here is the code I am using:

CSS

.gallery {
      margin: 5px;
      border: 1px solid #ccc;
      float: left;
      display: inline;
      width:180px;
      height:180px;
    }

    .gallery:hover {
        border: 1px solid #777;
    }

    .gallery img {
        max-height:100%;
        max-width:100%;
        margin:0 auto;
    }

HTML/PHP

<div class="gallery-container">
<?php
    $count = 0;
    foreach($images as $image) {
        echo "<div class='gallery'><a href=''><img src='".$dir.$image."'/></a></div>"; //$dir is the path to the image
        if(count % 4 == 0) {
            echo "<br>";
        }
        $count = $count + 1;
    }
?>
</div>

Here is a screenshot of the result on the first row: enter image description here

All the other rows come out fine. Thank you very much for any help.

Answers


xxxmatko February 2016

Instead of br element render "clear" div

<div style="clear:both"></div>


Jeremythuff February 2016

Checkout the resulting html. It is likely that you count is off and the br is being put to the dom too often. This fiddle shows that your desired html and css should work.

<div class='gallery'><a href=''><img src='https://upload.wikimedia.org/wikipedia/commons/b/b2/Hausziege_04.jpg'/></a></div>
<div class='gallery'><a href=''><img src='https://upload.wikimedia.org/wikipedia/commons/b/b2/Hausziege_04.jpg'/></a></div>
<div class='gallery'><a href=''><img src='https://upload.wikimedia.org/wikipedia/commons/b/b2/Hausziege_04.jpg'/></a></div>
<div class='gallery'><a href=''><img src='https://upload.wikimedia.org/wikipedia/commons/b/b2/Hausziege_04.jpg'/></a></div>
<br>

Though, I would consider not using the br, but instead using a containing div:

like this


Carlene February 2016

Have you tried starting the count at 1 instead of 0?


Trix February 2016

If you want to do it using float, you would better do that like this:

CSS

.gallery{
  margin: 5px;
  border: 1px solid #ccc;
  float: left;
  display: block;
  width:180px;
  height:180px;
}
.gallery.clear-left{
  clear: left;
}

PHP/HTML

<div class="gallery-container">
<?php
    $count = 0;
    foreach( $images as $image ){?>
        <div class="gallery <?php echo( 0 == $count % 4 ? 'clear-left' : '' );?>">
            <a href="">
                <img src="<?php echo $dir.$image;?>">
            </a>
        </div>
    <?php
        $count++;
    }
?>
</div>

But there is an even better solution to this, called flex:

Post Status

Asked in February 2016
Viewed 1,738 times
Voted 6
Answered 4 times

Search




Leave an answer


Quote of the day: live life