0

so I am trying to create a simple image gallery using HTML and CSS, here's my code below

img{
 float:left;
 width: 30%;
 margin: 1.66%;
}
<!DOCTYPE html>
<html>
<head>
 <title>Gallery</title>
 <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>


 <img src="IMG_1.jpg">
 <img src="IMG_2.jpg">
 <img src="IMG_3.jpg">

 <img src="IMG_4.jpg">
 <img src="IMG_5.jpg">
 <img src="IMG_6.jpg">

 <img src="IMG_7.jpg">
 <img src="IMG_8.jpg">
 <img src="IMG_9.jpg">
</body>
</html>

and I should expect to get a 3*3 image grid, but here is what I got
what I got

there is HUGE whitespace at the left of the second row. when I inspect it, the blank doesn't belong to any of the images. WHY!

enamoria
  • 896
  • 2
  • 11
  • 29

2 Answers2

1

Try this 100% it will work

.gallery{
    display: flex;
    flex-wrap: wrap;
}
img{
    width: 30%;
    margin: 1.66%;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Gallery</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>

    <div class="gallery">
      <img src="https://picsum.photos/536/354">
      <img src="https://picsum.photos/536/354">
      <img src="https://picsum.photos/536/354">

      <img src="https://picsum.photos/536/354">
      <img src="https://picsum.photos/536/354">
      <img src="https://picsum.photos/536/354">

      <img src="https://picsum.photos/536/354">
      <img src="https://picsum.photos/536/354">
      <img src="https://picsum.photos/536/354">
    </div>
  </body>
</html>
Par Tha
  • 1,265
  • 7
  • 10
0

Try to use flex, rather than float.

Wrap that images inside div:

<div class="img-container">
    <img src="IMG_1.jpg">
    <img src="IMG_2.jpg">
    ...
</div>

And use this style:

.img-container {
    display: flex;
    flex-wrap: wrap;
 }

 img{
    /*float:left;*/
    width: 30%;
    margin: 1.66%;
 }