CSS: fluid image gallery

A fluid CSS image gallery is an image gallery that will always fit the browser's viewport, regardless of the screen resolution. To accomplish this task, we need to use percentages to style all the components of our image gallery, including images. To begin with, we start with a simple unordered list that will contain our image gallery:

<ul id="gallery">

 <li>
   <a href="#">
     <img src="path/to/1.jpg" alt="Image 1" />
   </a>
 </li>
    <!--more items-->
</ul>

Percentages are calculated with respect to the parent element. So:

#gallery {
 padding: 2em 0;
 margin: 0 auto;
 width: 60%;
 list-style: none;
 height: 100%;
 overflow: hidden;
}

The width of the main container is set to 60%. Since its parent is the body element, this means 60% of the whole page. Then:

#gallery li {
 float: left;
 width: 45%;
 margin: 0 5px 0 0;
 padding-bottom: 5px;
}

The width of each item is set to 45%. In this case, this length refers to the parent element, that is, the gallery element. Finally:

#gallery li a {
 float: left;
 width: 100%;
 display: block;
}

#gallery li a img {
 display: block;
 width: 100%;
}

Both link and image widths are set to 100%. which refers to the width of each list item that contains them. If you change the browser's viewport width, the result will be always as depicted here:

You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “CSS: fluid image gallery”

  1. hello together,
    thanx for that great tutorial
    but i got stupid question
    how can i get 3 or 4 picture in a role
    best regards
    andy

Leave a Reply

Note: Only a member of this blog may post a comment.