Vanilla CSS Gallery

A simple image gallery made purely out of CSS. No JavaScript. Suitable for when you need a really simple and lightweight solution.

View on GitHub - By @jelmerdemaat - Share on Twitter


Example (with styling)

Click the images to interact with the gallery.

Example (without styling)



Necessary CSS

Core functionality.

.gallery-nav {
  /* To be able to have a z-index: */
  position: relative;
}

.gallery-close {
  /* Hide closing "x" initially: */
  display: none;
}

.gallery-item {
  /* Define the initial state: */
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  z-index: -1;
}

.gallery-item:target {
  /* When the image is active, make it appear: */
  opacity: 1;
  z-index: 2;
}

.gallery-item:target ~ .gallery-nav {
  /* Make the original image list also the gallery navigation: */
  z-index: 3;
}

.gallery-item:target ~ .gallery-nav .gallery-close {
  display: block;
}

Additional CSS

An example for more pretty styling. No prefixes included.

.gallery-item {
  background: black;
  background: rgba(0, 0, 0, 0.85);
  transition: opacity 0.3s ease-out;
}

.gallery-item img {
  max-width: 90vw;
  max-height: 90vh;
}

.gallery-item:target ~ .gallery-nav {
  top: 25px;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  position: fixed;
}

.gallery-item:target ~ .gallery-nav li {
  margin: 0 5px 0 0;
}

.gallery-item:target ~ .gallery-nav img {
  border: 2px solid white;
}

.gallery-item:target ~ .gallery-nav .gallery-close {
  font-size: 20px;
  font-weight: bold;
  background: rgba(0, 0, 0, 0.85);
  border-radius: 3px;
  display: block;
  position: absolute;
  left: 105%;
  top: 0;
}

.gallery-item img {
  margin: auto;
  border: 4px solid white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.gallery-close a {
  color: white;
  text-decoration: none;
  padding: 5px;
}

img {
  vertical-align: top;
}

Markup structure


<div class="gallery-item" id="1">
	<img src="images/beach.jpg" alt="A nice image of a beach" />
</div>
<div class="gallery-item" id="2">
	<img src="images/coffee.jpg" alt="A nice image of coffee" />
</div>
<div class="gallery-item" id="3">
	<img src="images/mountains.jpg" alt="A nice image of mountains" />
</div>

<ul class="gallery-nav">
	<li>
		<a href="#1">
			<img src="images/beach.jpg" alt="A nice beach image" />
		</a>
	</li>
	<li>
		<a href="#2">
			<img src="images/coffee.jpg" alt="A nice coffee image" />
		</a>
	</li>
	<li>
		<a href="#3">
			<img src="images/mountains.jpg" alt="A nice mountains image" />
		</a>
	</li>
	<li class="gallery-close">
		<a href="#deselect">&times;</a></li>
	<li>
</ul>