Skip to main content

CSS Image Gallery

When a web page shows a collection of images in an organized, and often responsive, way, that is a CSS image gallery.

Its HTML has two levels:

  • An outer container element wrapping the whole gallery (like a <div> as the gallery wrapper).
  • Inside it, one more container element per image (like a <div> per gallery item), holding the <img> tag and possibly a description.

Example

A basic image gallery built with flexbox, in HTML and CSS:

Prompt
Create a CSS image gallery using flexbox. The gallery container (div.gallery) uses display: flex and flex-wrap: wrap with justify-content: flex-start. Each gallery item (div.gallery-item) has margin 5px, border 1px solid #ccc, and width 180px. On hover the border changes to 1px solid #777. Images inside gallery items have width 100% and height auto. The description div (div.desc) has padding 15px and text-align center. Include four images: Cinque Terre (img_5terre.jpg), Forest (img_forest.jpg), Northern Lights (img_lights.jpg), and Mountains (img_mountains.jpg). Each image is wrapped in an anchor tag with target="_blank" and has width="600" height="400" attributes. Add a description text below each image.
Output: complete HTML page

CSS Responsive Image Gallery

With CSS media queries, the images re-arrange themselves according to the screen size:

  • On screens wider than 768px - four images appear side by side
  • On screens narrower than 768px - two images appear side by side
  • On screens narrower than 480px - the images stack vertically (width: 100%)

Example

Prompt
Create a responsive CSS image gallery using flexbox and media queries. The gallery container (div.gallery) uses display: flex and flex-wrap: wrap with justify-content: flex-start. Each gallery item (div.gallery-item) has margin 5px, border 1px solid #ccc, and uses percentage widths that change based on screen size. On hover the border changes to 1px solid #777. Images inside gallery items have width 100% and height auto. The description div (div.desc) has padding 15px and text-align center. Use media queries so that: if the screen is larger than 768px wide, show four images side by side (each item about 24%); if the screen is smaller than 768px, show two images side by side (each item about 48%); if the screen is smaller than 480px, stack images vertically (each item 100% width). Include four images: Cinque Terre (img_5terre.jpg), Forest (img_forest.jpg), Northern Lights (img_lights.jpg), and Mountains (img_mountains.jpg). Each image is wrapped in an anchor tag with target="_blank" and has width="600" height="400" attributes.
Output: complete HTML page