How to Create a Responsive CSS Centered Image in CSS3

Share this article

Image gallery lightboxes have been around for many years. They generally provide a great user experience until you attempt to load an image which is larger than the viewport dimensions. Developers often forget this important check and you’re presented with a centered image which is difficult to remove. The problem can be exacerbated on mobile devices. Until recently, image lightboxes would need to implement several equations to determine the viewport and image dimensions then size and center accordingly. Fortunately, we can now rely on CSS3 media queries and transforms to do the hard work for us. View the demonstration…

The HTML

Little to see here — we have an img and we’ll assign a class of “ri” (responsive image):
<img src="https://lorempixel.com/600/450/" class="ri" />
Remember to remove any height and width attributes.

Fallback CSS

IE6/7/8 do not understand media queries or transforms so our image will end up in the wrong location. There are shims and proprietary properties which could solve this but, in my opinion, they often cause more problems than they solve, i.e. increased page weight, degraded performance, maintenance headaches, etc. Therefore, the following code provides a reasonable fallback for legacy browsers and should work on most landscape-oriented desktop screens:
img.ri
{
	position: absolute;
	max-width: 80%;
	top: 10%;
	left: 10%;
	border-radius: 3px;
	box-shadow: 0 3px 6px rgba(0,0,0,0.9);
}
The border-radius and box-shadow
won’t be understood by old IEs either, but they’ll degrade gracefully.

Positioning the Image

To center the image with CSS, we move its top-left corner to the center of the viewport. To move it back to the true center, we use an appropriate transform (with prefixes for older browsers):
img.ri:empty
{
	top: 50%;
	left: 50%;
	-webkit-transform: translate(-50%, -50%);
	-moz-transform: translate(-50%, -50%);
	-ms-transform: translate(-50%, -50%);
	-o-transform: translate(-50%, -50%);
	transform: translate(-50%, -50%);
}
Take note of the selector: img.ri:emptyempty is a structural pseudo-class which only matches elements which have no children (an image should never have any). This is a CSS3 selector so IE8 and below will not parse the declaration. We could have used an alternative, such as Conditional Comments, but this seems a far more efficient solution and requires just six additional characters.

Making the Image Responsive

Our image must respond to the viewport dimensions to ensure it never overlaps the edge:
  • a maximum width must be defined if the viewport is taller than it is wide, and
  • a maximum height must be defined if the viewport is wider than it is tall.
We can use the media query orientation property to do the hard work for us:
@media screen and (orientation: portrait) {
  img.ri { max-width: 90%; }
}

@media screen and (orientation: landscape) {
  img.ri { max-height: 90%; }
}
Simple — and all done without any complicated JavaScripting. View the demonstration…
Please use the code as you like for your own projects. It could be used as the basis of your own modern, lightweight lightbox. Unless you’d like me to write one and provide a handy tutorial? Please forward your requests to @craigbuckler. And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Jump Start Responsive Web Design. Comments on this article are closed. Have a question about CSS3? Why not ask it on our forums?

Frequently Asked Questions (FAQs) about CSS3 Responsive Centered Image

What is a CSS3 Responsive Centered Image?

A CSS3 Responsive Centered Image is an image that is centered on a webpage and adjusts its size based on the size of the viewport. This is achieved using CSS3, the latest version of Cascading Style Sheets, a style sheet language used for describing the look and formatting of a document written in HTML. The image remains centered and maintains its aspect ratio as the viewport is resized, providing a better user experience on different devices.

How do I make an image responsive in CSS?

To make an image responsive in CSS, you need to set the width of the image to 100% and the height to auto. This allows the image to scale down if it has to, but it won’t scale up to be larger than its original size. Here’s a simple code snippet:
img {
max-width: 100%;
height: auto;
}
This code ensures that the image maintains its original aspect ratio and the image is scaled according to the width of its container.

How can I center an image using CSS?

To center an image using CSS, you can use the margin property. Set the left and right margins to auto and use the display property to set the value to block. Here’s a simple code snippet:
img {
display: block;
margin-left: auto;
margin-right: auto;
}
This code centers the image horizontally within its container.

Why is my image not responsive?

If your image is not responsive, it could be due to several reasons. The most common reason is that the width and height properties of the image are set to fixed values. To make the image responsive, you need to set the width to 100% and the height to auto. Another reason could be that the container of the image has a fixed width and height. In this case, you need to make the container responsive as well.

How can I make a background image responsive in CSS?

To make a background image responsive in CSS, you can use the background-size property and set its value to cover. This scales the background image to be as large as possible so that the background area is completely covered by the image. Here’s a simple code snippet:
body {
background-image: url('image.jpg');
background-size: cover;
}
This code ensures that the background image covers the entire body of the webpage.

How can I center a responsive image vertically and horizontally?

To center a responsive image vertically and horizontally, you can use a combination of CSS properties. Here’s a simple code snippet:
.container {
display: flex;
justify-content: center;
align-items: center;
}
This code centers the image both vertically and horizontally within its container.

How can I make an image responsive without CSS?

While CSS is the most common way to make an image responsive, you can also use HTML5’s picture element. The picture element allows you to specify multiple sources for an image and the browser will choose the most suitable one based on the current viewport size.

How can I make an image fill its container without stretching?

To make an image fill its container without stretching, you can use the object-fit property in CSS and set its value to cover. This scales the image to cover the container while maintaining its aspect ratio.

How can I make an image responsive in Bootstrap?

In Bootstrap, you can make an image responsive by adding the .img-fluid class to your image. This applies max-width: 100%; and height: auto; to the image so it scales with the parent element.

How can I make a div background image responsive?

To make a div background image responsive, you can use the background-size property and set its value to cover. This scales the background image to be as large as possible so that the background area is completely covered by the image.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

HTML5 Dev CenterimageresponsiveResponsive Design
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week