CSS - Centered Thumbnail Display

From NoskeWiki
Jump to navigation Jump to search
Thumbnails of different sizes aligned in the middle of a div


NOTE: This page is a daughter page of: CSS

Often you won't know the size of an image you want to display, and you'll want to just align it centered, vertically and horizontally, in a box (a separate div). Here is some CSS that does just that. The important parts come from the fantastic webpage: Centering in CSS: A Complete Guide. To align an object of unknown size horizontally and vertically:

.parent {
  position: relative;
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

The rest below is just some nice color and formatting.

Centered Thumbnail Display

<html lang="en"><head>
  <title>Centered Thumbnail Display</title>
h1 {
  color: maroon;
  font-size: 120%;
.image_box {
  background-color: #fafafa;
  height: 160px;
  width: 160px;
  border-style: solid;
  border-width: 1px;
  border-color: #eaeaea;
  display: inline-block;
  position: relative;
.image_thumbnail {
  max-height: 160px;
  max-width: 160px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);


<h1>Centered Thumbnail Display</h1>

Some fun images of different sizes/aspects:<br>

<div class="image_box"><img src="http://lorempixel.com/800/1200/" class="image_thumbnail" title="Hello"></div>

<div class="image_box"><img src="http://lorempixel.com/800/520/" class="image_thumbnail" title="Hello"></div>

<div class="image_box"><img src="http://lorempixel.com/400/400/" class="image_thumbnail" title="Hello"></div>

<div class="image_box"><img src="http://lorempixel.com/80/80/" class="image_thumbnail" title="Hello"></div>