Cloudinary Blog

Image Resizing: Manually With CSS and Automatically With Cloudinary

Image Resizing: Manually With CSS and Automatically With Cloudinary

With Cascading Style Sheets (CSS), you can change the size and aspect ratio of images and backgrounds. Three resizing options are available: absolute resizing, retention of the aspect ratio, and relative resizing. You can also scale and fill backgrounds. However, those are all manual chores that take time, skill, and effort.

With Cloudinary, you can easily transform images, including resizing them and their backgrounds. This article explains how to manually do those tasks with CSS and through an automated, AI-based process in Cloudinary.

Here are the topics:

Resize Images With CSS3

You can resize images with CSS3, the latest CSS version, in one of three ways, as described below. Pick your choice according to the values of the height and width properties you desire.

Absolute Resizing

With absolute resizing, you specify the height and width values along with the static ones in pixels (px), ems (em), or another absolute-size format. See this example:

Copy to clipboard
img{
  height: 100px;
  width: 200px;
}

Retention of Aspect Ratio

To retain the aspect ratio, statically modify either the height or width value and set auto for the other property to enable automatic sizing, as in this example:

Copy to clipboard
img{
  height: 100px;
  width: auto;
}

Relative Sizing

Relative sizing means sizing images according to the parent <div> or the size of the client viewport. If you apply that property to an image as the only element, the parent container is the viewport. Setting object-fit: contain retains the image’s original dimensions. CSS then sizes to the point at which the entire image is visible.

This example sizes an image to fit the space available in the parent container:

Copy to clipboard
img{
  height: 100%;
  width: 100%;
  object-fit: contain;
}

Resize Backgrounds With CSS3

Say you want to resize a background image to better fit an element or your page. The background-size property would come in handy. See the examples below.

Absolute Resizing

Similar to resizing with standard images, absolute resizing changes the background dimensions to match the height and width you specify. Keep in mind that manually setting values also changes the aspect ratio.

To resize backgrounds, specify the width first and then the height. Omitting the height defaults it to auto. For example, the three codelines below produce the same image size, assuming that the image starts as 200px by 200px:

Copy to clipboard
background-size: 100px 100px;

background-size: 100px;

background-size: 100px auto;

Relative Sizing

Relative sizing works in the same way as absolute resizing, as described above, except that, here, you specify the value for the background-size property instead of the values for height and width. For example:

Copy to clipboard
  background-size: 50% auto;

Maximum Scaling

To automatically resize your background to the maximum that the parent element can hold, specify the contain value—just like what you do for object-fit. The background then automatically tiles to fill any remaining space.

To stop that behavior, add the background-repeat property. However, such a setup leaves any space that cannot be filled with the single-image blank.

Here’s an example:

Copy to clipboard
background-size: contain;
Background-repeat: no-repeat;

Background Filling

To apply an effect similar to contain but with no blank space, specify the cover value to fill the container element of the background but crop off any excess image outside the container, like this:

Copy to clipboard
background-size: cover;

For more ways to transform images in CSS, see our article on CSS’s image effects and filter.

Crop Images Automatically With Cloudinary

A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload your images, apply built-in effects, filters, and modifications. You can also resize images automatically, focusing on the most important elements with AI or adapt them to your website design without having to manually crop or scale them.

Additionally, you can transform images programmatically with SDKs or simple URL parameters. Cloudinary applies changes dynamically, leaving your original images intact. That means you can modify images on the fly to adapt to design changes—a huge convenience and time saver.

Resize and Rescale Images Automatically With Cloudinary

Below are three ways to resize element or background images with Cloudinary’s URL parameters. Each of the sections below links you to the Cloudinary Cookbook page with more details.

Limit Images to Specific Dimensions

To limit the size of an image to certain dimensions, change the crop (c in URLs) value to limit.

Below is an image that’s been resized from 850 x 565 px. to 70 x 70 px. with limit. Due to the preserved aspect ratio, this display is 70 x 47 px.

Ruby:
Copy to clipboard
cl_image_tag("cashew_chicken.jpg", :width=>70, :height=>70, :crop=>"limit")
PHP v1:
Copy to clipboard
cl_image_tag("cashew_chicken.jpg", array("width"=>70, "height"=>70, "crop"=>"limit"))
PHP v2:
Copy to clipboard
(new ImageTag('cashew_chicken.jpg'))
  ->resize(Resize::limitFit()->width(70)->height(70));
Python:
Copy to clipboard
CloudinaryImage("cashew_chicken.jpg").image(width=70, height=70, crop="limit")
Node.js:
Copy to clipboard
cloudinary.image("cashew_chicken.jpg", {width: 70, height: 70, crop: "limit"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().width(70).height(70).crop("limit")).imageTag("cashew_chicken.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('cashew_chicken.jpg', {width: 70, height: 70, crop: "limit"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("cashew_chicken.jpg", {width: 70, height: 70, crop: "limit"})
React:
Copy to clipboard
<Image publicId="cashew_chicken.jpg" >
  <Transformation width="70" height="70" crop="limit" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="cashew_chicken.jpg" >
  <cld-transformation width="70" height="70" crop="limit" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="cashew_chicken.jpg" >
  <cl-transformation width="70" height="70" crop="limit">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Width(70).Height(70).Crop("limit")).BuildImageTag("cashew_chicken.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().width(70).height(70).crop("limit")).generate("cashew_chicken.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setWidth(70).setHeight(70).setCrop("limit")).generate("cashew_chicken.jpg")!, cloudinary: cloudinary)
crop limit

Crop Images With Auto Gravity

To focus on certain details—faces, objects, color contrasts—while resizing images, crop the images with Cloudinary's intelligent auto-gravity features. The parameter to set is gravity (g in URLs), which offers an auto value that intelligently crops according to your image’s content.

Cloudinary automatically crops images with content-aware, AI-based features by selecting faces, individual features, or areas of interest. To trigger that task, apply the gravity filter (g) with the features you want to preserve.

This example with the g_auto setting crops the most interesting area, as determined by AI:

auto gravity

Another example: to avoid irrelevant objects instead of the product in product images taking center stage, define the product as the focus. The picture on the right below has the backpack in focus.

Ruby:
Copy to clipboard
cl_image_tag("veducate/spencer-backman-482079-unsplash.jpg", :gravity=>"auto:classic", :height=>175, :width=>175, :crop=>"thumb")
PHP v1:
Copy to clipboard
cl_image_tag("veducate/spencer-backman-482079-unsplash.jpg", array("gravity"=>"auto:classic", "height"=>175, "width"=>175, "crop"=>"thumb"))
PHP v2:
Copy to clipboard
(new ImageTag('veducate/spencer-backman-482079-unsplash.jpg'))
  ->resize(Resize::thumbnail()->width(175)->height(175)
    ->gravity(Gravity::autoGravity()
      ->autoFocus(AutoFocus::focusOn(FocusOn::classic()))));
Python:
Copy to clipboard
CloudinaryImage("veducate/spencer-backman-482079-unsplash.jpg").image(gravity="auto:classic", height=175, width=175, crop="thumb")
Node.js:
Copy to clipboard
cloudinary.image("veducate/spencer-backman-482079-unsplash.jpg", {gravity: "auto:classic", height: 175, width: 175, crop: "thumb"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().gravity("auto:classic").height(175).width(175).crop("thumb")).imageTag("veducate/spencer-backman-482079-unsplash.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('veducate/spencer-backman-482079-unsplash.jpg', {gravity: "auto:classic", height: 175, width: 175, crop: "thumb"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("veducate/spencer-backman-482079-unsplash.jpg", {gravity: "auto:classic", height: 175, width: 175, crop: "thumb"})
React:
Copy to clipboard
<Image publicId="veducate/spencer-backman-482079-unsplash.jpg" >
  <Transformation gravity="auto:classic" height="175" width="175" crop="thumb" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="veducate/spencer-backman-482079-unsplash.jpg" >
  <cld-transformation gravity="auto:classic" height="175" width="175" crop="thumb" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="veducate/spencer-backman-482079-unsplash.jpg" >
  <cl-transformation gravity="auto:classic" height="175" width="175" crop="thumb">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Gravity("auto:classic").Height(175).Width(175).Crop("thumb")).BuildImageTag("veducate/spencer-backman-482079-unsplash.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().gravity("auto:classic").height(175).width(175).crop("thumb")).generate("veducate/spencer-backman-482079-unsplash.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setGravity("auto:classic").setHeight(175).setWidth(175).setCrop("thumb")).generate("veducate/spencer-backman-482079-unsplash.jpg")!, cloudinary: cloudinary)
g_auto:classic Transformation Applied to It g_auto:classic
Ruby:
Copy to clipboard
cl_image_tag("veducate/spencer-backman-482079-unsplash.jpg", :gravity=>"auto:backpack", :height=>175, :width=>175, :crop=>"thumb")
PHP v1:
Copy to clipboard
cl_image_tag("veducate/spencer-backman-482079-unsplash.jpg", array("gravity"=>"auto:backpack", "height"=>175, "width"=>175, "crop"=>"thumb"))
PHP v2:
Copy to clipboard
(new ImageTag('veducate/spencer-backman-482079-unsplash.jpg'))
  ->resize(Resize::thumbnail()->width(175)->height(175)
    ->gravity(Gravity::autoGravity()
      ->autoFocus(AutoFocus::focusOn(FocusOn::backpack()))));
Python:
Copy to clipboard
CloudinaryImage("veducate/spencer-backman-482079-unsplash.jpg").image(gravity="auto:backpack", height=175, width=175, crop="thumb")
Node.js:
Copy to clipboard
cloudinary.image("veducate/spencer-backman-482079-unsplash.jpg", {gravity: "auto:backpack", height: 175, width: 175, crop: "thumb"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().gravity("auto:backpack").height(175).width(175).crop("thumb")).imageTag("veducate/spencer-backman-482079-unsplash.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('veducate/spencer-backman-482079-unsplash.jpg', {gravity: "auto:backpack", height: 175, width: 175, crop: "thumb"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("veducate/spencer-backman-482079-unsplash.jpg", {gravity: "auto:backpack", height: 175, width: 175, crop: "thumb"})
React:
Copy to clipboard
<Image publicId="veducate/spencer-backman-482079-unsplash.jpg" >
  <Transformation gravity="auto:backpack" height="175" width="175" crop="thumb" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="veducate/spencer-backman-482079-unsplash.jpg" >
  <cld-transformation gravity="auto:backpack" height="175" width="175" crop="thumb" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="veducate/spencer-backman-482079-unsplash.jpg" >
  <cl-transformation gravity="auto:backpack" height="175" width="175" crop="thumb">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Gravity("auto:backpack").Height(175).Width(175).Crop("thumb")).BuildImageTag("veducate/spencer-backman-482079-unsplash.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().gravity("auto:backpack").height(175).width(175).crop("thumb")).generate("veducate/spencer-backman-482079-unsplash.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setGravity("auto:backpack").setHeight(175).setWidth(175).setCrop("thumb")).generate("veducate/spencer-backman-482079-unsplash.jpg")!, cloudinary: cloudinary)
backback g_auto:backpack

Learn More About Cloudinary

Besides the image-resizing capability, Cloudinary offers a multitude of robust tools for web developers, including the following:

  • Automated image uploads. You can upload images at scale anywhere from a browser, mobile app, or application back-end directly to the cloud.
  • Generous image storage. Cloudinary accords you up to 25 GB free managed, secure, and cloud-based storage space with multiregion backup, revision history, and disaster recovery.
  • Seamless asset management. You can efficiently manage your image library on Cloudinary by performing tasks like searching, organizing, and tagging files; controlling access; and monitoring usage and performance.
  • Effective image transformation. You can transform, enhance, transcode, crop, scale, and enhance images with a URL-based API or with SDKs that support all popular programming languages.
  • Automated image optimization. Cloudinary automatically selects the optimal quality and encoding settings for images, adapts the settings to any resolution or pixel density, and scales or crops images to focus on the important regions.
  • Responsive images. Cloudinary automatically scales images in an art-directed manner, cropping them to fit different resolutions and viewports.
  • Reliable and fast image delivery. Cloudinary delivers images through Content Delivery Networks (CDNs)—Akamai, Fastly, and CloudFront—with no integration or management on your part.

Do give Cloudinary a try. To start, sign up for a free account.

Check Out the Details of CSS Images

Want to learn more about CSS images? These articles are an excellent resource:

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more