惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Privacy International News Feed
I
Intezer
T
Tenable Blog
S
Schneier on Security
Project Zero
Project Zero
G
GRAHAM CLULEY
酷 壳 – CoolShell
酷 壳 – CoolShell
小众软件
小众软件
Know Your Adversary
Know Your Adversary
博客园 - 司徒正美
The Cloudflare Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
N
News and Events Feed by Topic
博客园 - 叶小钗
宝玉的分享
宝玉的分享
L
LINUX DO - 热门话题
aimingoo的专栏
aimingoo的专栏
S
Secure Thoughts
Forbes - Security
Forbes - Security
T
The Exploit Database - CXSecurity.com
D
Darknet – Hacking Tools, Hacker News & Cyber Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
罗磊的独立博客
IT之家
IT之家
H
Hacker News: Front Page
I
InfoQ
云风的 BLOG
云风的 BLOG
S
Security Affairs
M
MIT News - Artificial intelligence
GbyAI
GbyAI
Jina AI
Jina AI
Help Net Security
Help Net Security
Engineering at Meta
Engineering at Meta
大猫的无限游戏
大猫的无限游戏
Webroot Blog
Webroot Blog
L
Lohrmann on Cybersecurity
A
About on SuperTechFans
Attack and Defense Labs
Attack and Defense Labs
The Register - Security
The Register - Security
V
V2EX
G
Google Developers Blog
D
DataBreaches.Net
Apple Machine Learning Research
Apple Machine Learning Research
C
Cybersecurity and Infrastructure Security Agency CISA
J
Java Code Geeks
W
WeLiveSecurity
Cloudbric
Cloudbric
T
Tor Project blog

ImageKit.io Blog

Next.js Image Optimization with ImageKit Use Video as a Background in Your Next.js Project How to Fix Autoplay Video in Next.js How Durian Scaled a Visual-First Retail Experience to 350K Monthly Visitors Online How Matsmart accelerated image delivery across countries with ImageKit AI in Digital Asset Management: From Smart Workflows to Agentic Automation How Joseph Joseph unified and secured global video delivery with ImageKit How Modall powers fast, effortless media delivery across 40+ projects with ImageKit Digital Asset Management (DAM) Trends: 2026 Report How to add a poster image to Video.js player (and automate it) HLS streaming with Video.js + React Building the future of storytelling with fast, AI-powered video delivery How PushOwl delivers 100M+ image-rich notifications seamlessly with ImageKit How Homify delivers millions of interior design images seamlessly with ImageKit Better event discovery with lightning‑fast videos & images Adding video player in React Native Video player in Angular applications Crop and resize videos in React Next.js image and video upload React image and video upload React video optimization How we quadrupled our traffic to 625K monthly page views How Apollo 24|7 boosted performance & reduced costs with ImageKit Simplify your media workflows with ImageKit DAM integrations Extending Lighthouse for custom image and video optimization analysis Brand Asset Management: What is it? How does it work? WordPress Digital Asset Management Guide - Manage your WP media assets better Why Shopify retailers need a digital asset management solution DAM vs. SharePoint: Which is best for you? AI-powered Metadata and Tagging in Digital Asset Management How Hopscotch built India's largest online Kids' fashion brand with ImageKit Dropbox Vs. DAM: Which Is The Right Tool For Digital Asset Management Digital Asset Management for Photographers: A Complete Guide Why digital asset management for agencies is essential Helping both Top and Bottom Line: SaffronStays rapid, profitable growth with ImageKit How KreditBee simplified media experiences with ImageKit Google Drive alternatives for businesses (with fast-growing teams) Node.js image upload ImageKit: The Secret Ingredient in Swiggy’s Expansion Journey Streamlining the Design Approval Process: A Comprehensive Guide AV1 Codec - Complete guide for video application devs PHP image and video upload Angular image & video upload AV1 vs VP9: Which codec should you choose? Adding video player in Next.js React Video Player VP8 vs VP9 - In the context of online video delivery Exploring WebM vs MP4 7 Free Digital Asset Management Software that are not Open-Source Comparing 9 Top Digital Asset Management Tools in the Market What are Brand Standards and Why do they Matter? Boost Sales and Brand Appeal: Essential Tips for eCommerce Image Management Brand Recall: The Strategy to Create Unforgettable Brands How to upload files in HTML? Branding for Small Businesses (2025 Edition) Everything you need to know about VP9 codec Recent updates from ImageKit and what's next Best Ways to Write RFP For Digital Asset Management (+ with free RFP template) What is Brand Dilution? How to Avoid It? Explained with [Examples] The Importance of Brand Identity: Leveraging Digital Asset Management for Impact From Launch to Scale: How to Launch a Brand Campaign Digital Asset Management Requirements - What do You Need to Evaluate and How? Marketing Collateral Management: A Quick End-to-End Guide Video Content Management System: What Is It And How To Choose One? Dropbox vs. Google Drive vs. Onedrive: The Best Cloud Storage Solution How to Build Brand Trust: Get Started In 2025 Google Drive vs. Box: A Detailed Comparison How Digital Asset Management Solutions Help Protect Brand Equity A DAM Solution Can Safeguard Your Digital Intellectual Property - Here’s How WebP Vs. PNG: Which Image Format Should You Use and Why? How to Resize Images in Bootstrap Easily Progressive jpegs (PJPEG): the key to loading images faster on your website Dropbox vs. Google Drive: The Best Cloud Storage For Digital Assets Dropbox Pros & Cons In 2024: An In-Depth Analysis and Why A DAM Solution Stands Out Google Drive Vs OneDrive: The Better Storage Option For Digital Assets Manage your video assets better with video metadata Understanding DAM's Role in Strengthening Brand Identity Digital asset management strategy: What to know before creating one The Ultimate Guide To Marketing Agency Onboarding 6 Solutions To Simplify Large File Sharing Over The Web A Step-by-Step Breakdown of a Video Production Workflow 13 Digital Asset Management Use Cases You Should Know How to Conduct a Brand Audit and Manage Your Brand Assets Costly Consequences of Inconsistent Branding And How DAM Can Help Dynamic Asset Transformation: What It Is, Why You Need It, and How ImageKit Can Help Everything You Need to Know About HTML Video Autoplay How To Select Your DAM Vendor: A Complete Guide How to Boost User Experience with Smart Digital Asset Management React Image Optimization: A Guide for Web Developers Why Should DAM Be A Part Of Your MarTech Stack? Unleashing the Power of Content Repurposing with ImageKit MKV vs MP4: Which Video File Format Is Better for Your Needs? Digital Asset Management For Ecommerce: A Complete Guide How an Image Tagging Software can Transform Your Image Search How to Manage Your Content Lifecycle Effectively M4V vs MP4: Which Video Format Should You Use and Why? Why Every Business Needs An Image Management System All The Questions To Ask During A Dam Demo Which is the Best Image Format for Your Website? Uploading Multiple Files Using JavaScript: A Comprehensive Guide
How to resize an image in HTML?
Manu Chaudhary · 2020-12-10 · via ImageKit.io Blog

If your image doesn’t fit the layout, you can resize it in the HTML. One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.

For example, the original image is 640×960.

https://ik.imagekit.io/ikmedia/women-dress-2.jpg

We can render it with a height of 500 pixels and a width of 400 pixels

<img src="https://ik.imagekit.io/ikmedia/women-dress-2.jpg" 
     width="400" 
     height="500" />

If the image element's required height and width don’t match the image's actual dimensions, then the browser downscales (or upscale) the image. The exact algorithm used by the browser for scaling can vary and depends on the underlying hardware and OS.

There are a couple of downsides of client-side image resizing, mainly poor image quality and slower image rendering. To overcome this, you should serve already resized images from the server. You can use Thumbor or a free image CDN like ImageKit.io to resize images dynamically using URL parameters.

Resizing an image in CSS

You can also specify the height and width in CSS.

img {
  width: 400px,
  height: 300px
}

Preserving the aspect ratio while resizing images

When you specify both height and width, the image might lose its aspect ratio. You can preserve the aspect ratio by specifying only width and setting height to auto using CSS property.

img {
  width: 400px,
  height: auto
}

This will render a 400px wide image. The height is adjusted accordingly to preserve the aspect ratio of the original image. You can also specify the height attribute and set width as auto, but most layouts are generally width constrained and not height.

Responsive image which adjusts based on available width

You can specify the width in percentage instead of an absolute number to make it responsive. By setting width to 100%, the image will scale up if required to match the parent element’s width. It might result in a blurred image as the image can be scaled up to be larger than its original size.

img {
  width: 100%;
  height: auto;
}

Alternatively, you can use the max-width property. By setting

max-width:100%;

the image will scale down if it has to, but never scale up to be larger than its original size.

img {
  max-width: 100%;
  height: auto;
}

How to resize & crop image to fit an element area?

So far, we have discussed how to resize an image by specifying height or width or both of them.

When you specify both height and width, the image is forced to fit the requested dimension. It could change the original aspect ratio. At times, you want to preserve the aspect ratio while the image covers the whole area even if some part of the image is cropped. To achieve this, you can use:

  • Background image
  • object-fit css property

Resizing background image

background-image is a very powerful CSS property that allows you to insert images on elements other than img. You can control the resizing and cropping of the image using the following CSS attributes-

  • background-size - Size of the image
  • background-position - Starting position of a background image

background-size
By default, the background image is rendered at its original full size. You can override this by setting the height and width using the background-size CSS property.  You can scale the image upward or downward as you wish.

<style>
.background {
  background-image: url("/image.jpg");
  background-size: 150px;
  width: 300px;
  height: 300px;
  border: solid 2px red;
}
</style>

<div class="background">
</div>

Possible values of background-size:

  • auto - Renders the image at full size
  • length - Sets the width and height of the background image. The first value sets the width, and the second value sets the height. If only one value is given, the second is set to auto. For example, 100px 100px or 50px.
  • percentage - Sets the width and height of the background image in percent of the parent element. The first value sets the width, and the second value sets the height. If only one value is given, the second is set to auto. For example, 100% 100% or 50%.

It also has 2 special values contain and cover:

background-size:contains
contains - It preserves the original aspect ratio of the image, but the image is resized so that it is fully visible. The longest of either the height or width will fit in the given dimensions, regardless of the size of the containing box.

<style>
.background {
  background-image: url("/image.jpg");
  background-size: contains;
  width: 300px;
  height: 300px;
  border: solid 2px red;
}
</style>

<div class="background">
</div>

background-size:cover
cover - It preserves the original aspect ratio but resizes the image to cover the entire container, even if it has to upscale the image or crop it.

<style>
.background {
  background-image: url("/image.jpg");
  background-size: cover;
  width: 300px;
  height: 300px;
  border: solid 2px red;
}
</style>

<div class="background">
</div>

object-fit CSS property

You can use the object-fit CSS property on the img element to specify how the image should be resized & cropped to fit the container. Before this CSS property was introduced, we had to resort to using a background image.

Along with inherit, initial, and unset, there are 5 more possible values for object-fit:

  • contain: It preserves the original aspect ratio of the image, but the image is resized so that it is fully visible. The longest of either the height or width will fit in the given dimensions, regardless of the size of the containing box.
  • cover: It preserves the original aspect ratio but resizes the image to cover the entire container, even if it has to upscale the image or crop it.
  • fill: This is the default value. The image will fill its given area, even if it means losing its aspect ratio.
  • none: The image is not resized at all, and the original image size fills the given area.
  • scale-down: The smaller of either contain or none.

You can use object-position to control the starting position of the image in case a cropped part of the image is being rendered.

Let’s understand these with examples.

The following image’s original width is 1280px and height is 854px. Here it is stretching to maximum available width using max-width: 100%.

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
     style="max-width: 100%;" />
Backlit image at maximum width

object-fit:contains

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:contain;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>

The original aspect ratio of the image is same, but the image is resized so that it is fully visible. We have added 1px border around the image to showcase this.

object-fit contain example

object-fit:cover

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:cover;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>

The original aspect ratio is preserved but to cover the whole area image is clipped from the left and right side.

object-fit cover example

object-fit:fill

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:fill;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>

Image is forced to fit into a 200px wide container with height 300px, the original aspect ratio is not preserved.

object-fit fill example

object-fit:none

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:none;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>
object-fit none example

object-fit:scale-down

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:scale-down;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>
object-fit scale-down example

object-fit:cover and object-position:right

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:cover;
     		object-position: right;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>
object-fit cover with object-position right example

Downsides of client-side image resizing

There are certain downsides of client-side resizing that you should keep in mind.

1. Slow image rendering

Since the full-sized image is loaded anyway before resizing happens in the browser, it takes more time to finish downloading and finally rendering. This means that if you have a large, 1.5 megabyte, 1024×682 photograph that you are displaying at 400px in width, the whole 1.5-megabyte image is downloaded by the visitor before the browser resizes it down to 400px.

You can see this download time on the network panel, as shown in the screenshot below.

On the other hand, if you resize the image on the server using some program or an image CDN, then the browser doesn't have to load a large amount of data and waste time decoding & rendering it.

With ImageKit.io, you can easily resize an image using URL parameters. For example -

Original image
https://ik.imagekit.io/ikmedia/women-dress-2.jpg

400px wide image with aspect ratio preserved
https://ik.imagekit.io/ikmedia/women-dress-2.jpg?tr=w-400

2. Poor image quality

The exact scaling algorithm used by the browser can vary, and its performance depends upon underlying hardware and OS. When a relatively bigger image is resized to fit a smaller container, the final image could be noticeably blurry.

There is a tradeoff between speed and quality. The final choice depends upon the browser. Firefox 3.0 and later versions use a bilinear resampling algorithm, which is tuned for high quality rather than speed. But this could vary.

You can use the image-rendering CSS property, which defines how the browser should render an image if it is scaled up or down from its original dimensions.

/* Keyword values */
image-rendering: auto;
image-rendering: crisp-edges;
image-rendering: pixelated;

/* Global values */
image-rendering: inherit;
image-rendering: initial;
image-rendering: unset;

3. Bandwidth wastage

Since the full-sized image is being loaded anyway, it results in wastage of bandwidth, which could have been saved. Data transfer is not cheap. In addition to increasing your bandwidth bills, it also costs your users real money.

If you are using an image CDN, you can further reduce your bandwidth consumption by serving images in next-gen formats e.g. WebP or AVIF.

The user friendly dashboard will also show you how much bandwidth you have saved so far

See the actual savings in the ImageKit dashboard
See the actual savings in the ImageKit dashboard

4. Increased memory and processing requirements on client devices

Resizing large images to fit a smaller container is expensive and can be painful on low-end devices where both memory and processing power is limited. This slows down the whole web page and degrades the user experience.

Summary

When implementing web pages, images need to fit the layout perfectly. Here is what you need to remember to be able to implement responsive designs:

  • Avoid client-side (browser) resizing at all if you can. This means serve correctly sized images from the server. It results in less bandwidth usage, faster image loading, and higher image quality. There are many open-source image processing libraries if you want to implement it yourself. Or better, you can use a free image CDN which will provide all these features and much more with a few lines of code.
  • Never upscale a raster image i.e. JPEG, PNG, WebP, or AVIF images, should never be upscaled as it will result in a blurred output.
  • You should use the SVG format for icons and graphics if required in multiple dimensions in the design.
  • While resizing, if you want to preserve the aspect ratio of original images - Only specify one of width and height and set the other to auto.
  • If you want the image to fit the entire container while preserving the aspect ratio, even if some part is cropped or the image is upscaled - Use the object-fit CSS property or set a background image using the background-image CSS property.
  • Control the starting position of the image using object-position while using object-fit. In background images, use background-position.