object-fit

Resize image proportionally with CSS? [duplicate]

Is there a way to resize (scale down) images proportionally using ONLY CSS? I’m doing the JavaScript way, but just trying to see if this is possible with CSS.

Ethan Marcotte recently investigated this issue very thoroughly. The short answer is yes, it’s possible, but not in all browsers.

If you don’t want to burn bandwidth, slimmage.js can help; it reads the resulting max-width value to adjust which size image is requested.

18 Answers 18

To resize the image proportionally using CSS:

+1 You can also use max-width instead of width if desired. The key is to use height:auto to override any height=». » attribute already present on the image.

A common use is to set max-width: 100%; height: auto; so large images don’t exceed their containers width.

This doesn’t work if you want to make the image bigger. The image lose its aspect ratio. Unless, of course, the container has the same aspect ratio of the image.

Control size and maintain proportion :

Yep, this is the correct answer to the question as it takes into account image orientation (i.e. landscape vs. portrait). Thanks!

If it’s a background image, use background-size:contain.

transform: scale(0.5, 0.5); -ms-transform: scale(0.5, 0.5); -webkit-transform: scale(0.5, 0.5); 

Actually this works pretty well if you have to scale down each image proportionally to its size. With this code images become 2x smaller. +1 BUT! With this solution the images still take up the space!

@MārtiņšBriedis: Isn’t that the point? Is there a way to get images on the server to take up less space «using ONLY CSS» (see OP)?!

Not that kind of space. The images still have the same bounds, width, height in document, only they «look» 2 times smaller. Imagine — an image with size 100×100. Then you apply scale(0.5), and it is the same as image 50×50, but with invisible 25px borders on both sides. The image still would take up the 100×100 space. –

You can use object-fit property:

This will fit image, without changing the proportionally.

I use width 100% and height 100% and also object fit contain. and it works like a charm :). And object fit contain solution is simple

note the browser support: developer.mozilla.org/en-US/docs/Web/CSS/object-fit as of now, no IE and android 4.4.4+.

object-fit works well — just seems to require both height and width or both max-height and max-width to not cause the image to overflow the container in either direction.

Notice that width:50% will resize it to 50% of the available space for the image, while max-width:50% will resize the image to 50% of its natural size. This is very important to take into account when using this rules for mobile web design, so for mobile web design max-width should always be used.

Читайте также:  Java chars as numbers

UPDATE: This was probably an old Firefox bug, that seems to have been fixed by now.

True, thanks. But how do you handle the size wrapper of the image? It is still acting like the image is 100% wide instead of 50%, causing an unwanted border. I’d like it to fit tightly around the downscaled image.

The problem with this approach is that max-width has nothing to do with the original dimensions of the image. max-width of 50% means «50% of the width of the containing block». (Docs on width )

Источник

scale()

The scale() CSS function defines a transformation that resizes an element on the 2D plane. Because the amount of scaling is defined by a vector, it can resize the horizontal and vertical dimensions at different scales. Its result is a data type.

Try it

This scaling transformation is characterized by a two-dimensional vector. Its coordinates define how much scaling is done in each direction. If both coordinates are equal, the scaling is uniform (isotropic) and the aspect ratio of the element is preserved (this is a homothetic transformation).

When a coordinate value is outside the [-1, 1] range, the element grows along that dimension; when inside, it shrinks. A negative value results in a point reflection in that dimension. The value 1 has no effect.

Note: The scale() function only scales in 2D. To scale in 3D, use scale3d() instead.

Syntax

The scale() function is specified with either one or two values, which represent the amount of scaling to be applied in each direction.

Values

Cartesian coordinates on ℝ^2 Homogeneous coordinates on ℝℙ^2 Cartesian coordinates on ℝ^3 Homogeneous coordinates on ℝℙ^3
( sx 0 0 sy ) ( sx 0 0 0 sy 0 0 0 1 ) ( sx 0 0 0 sy 0 0 0 1 ) ( sx 0 0 0 0 sy 0 0 0 0 1 0 0 0 0 1 )
[sx 0 0 sy 0 0]

Accessibility concerns

Scaling/zooming animations are problematic for accessibility, as they are a common trigger for certain types of migraine. If you need to include such animations on your website, you should provide a control to allow users to turn off animations, preferably site-wide.

Also, consider making use of the prefers-reduced-motion media feature — use it to write a media query that will turn off animations if the user has reduced animation specified in their system preferences.

Источник

HTML img scaling

I’m trying to display some large images with HTML img tags. At the moment they go off the edge of the screen; how can I scale them to stay within the browser window? Or in the likely event that this is not possible, is it possible to at least say «display this image at 50% of its normal width and height»? The width and height attributes distort the image — as far as I can tell, this is because they refer to whatever attributes the container may end up with, which will be unrelated to the image. I can’t specify pixels because I have to deal with a large collection of images each with a different pixel size. Max-width doesn’t work.

Читайте также:  Java api for hadoop

Keep in mind that its not recommended to send huge images and make them small with css. It’s better to have different versions of the same image to save bandwidth and to make the page more responsive (even if the image will look small, the full image will be sent).

Image file size doesn’t matter, there is no requirement in the case I’m looking at to be frugal with bandwidth. I am using PHP, but the HTML solution works.

8 Answers 8

Only set the width or height , and it will scale the other automatically. And yes you can use a percentage.

The first part can be done, but requires JavaScript, so might not work for all users.

Please, please, please note that doing this on massive images will result in long download times for pages that shouldn’t have long download times. It’s always better to actually resize the image if possible.

Thanks! It turns out your solution of only setting the width not only works for correct scaling, but actually also does the first part just by setting the width to 100%.

@ceejayoz I’m wondering, why does it take longer? Doesn’t it have to resize when it displays it for both situations? Or are you saying manually resize the actual image and change the file?

@Abdul I’m saying a 3,000×3,000 pixel 5MB image shouldn’t be used in a 100×100 pixel slot in your website.

I know that this question has been asked for a long time but as of today one simple answer is:

The use of vw in here tells that the width is relative to 55% of the width of the viewport.

All the major browsers nowadays support this.

No Javascript required.

Percent only works for the width of an element, but height:100%; does not work without the correct code.

Then using a percentage works properly, and dynamically updates on window resize.

You do not need a width attribute, the width scales proportionately as the browser window size is changed.

And this little gem, is in case the image is scaled up, it will not look (overly) blocky (it interpolates).

or style=»height: 80%; image-rendering: pixelated;» for chrome (or other interpolation methods if needed, see here: developer.mozilla.org/en-US/docs/Web/CSS/image-rendering)

Adding max-width: 100%; to the img tag works for me.

I think the best solution is resize the images via script or locally and upload them again. Remember, you’re forcing your viewers to download larger files than they need

For an automatic letterbox/pillarbox in a fixed-size rectangle, use the object-fit CSS property. That is usually what I want, and it avoids using code to figure out which is the dominant dimension or — what I used to do — embedding an element with an child to wrap the content with its nice preserveAspectRatio options.

    :root < --box-side : min( 42vmin, 480px ) ; >body < align-items : center ; display : flex ; flex-wrap : wrap ; justify-content : center ; >body,html < height : 100% ; width : 100% ; >img              

Источник

Читайте также:  Javascript data types size

How can I scale all images to the same dimensional area? [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

I’m loading in several images. They are various lengths and widths, but I would like for them all to feel as though they are the same «size». So, if one image is 200×100 and another image is 200×400, I would like for them both to scale in such a way that they take up the same amount of space on the screen. If I fix the width to be 200, then the second element is 4 times the size of the first. For example:

produces this behavior How can I use css to fix the area of an image or other element? Where by area, I mean literally length times width. I would like to load in an image of arbitrary dimensions, and scale it (preserving aspect ratio) so that its area is fixed to be a given value.

@closevotes, can you clarify what needs more focus? I’m not sure precisely what two questions this is asking. My question is «how to use css to fix the area of an image?». If there are other questions hidden in here, I am happy to attempt to extricate them.

Your question criteria are unclear. «So, if one image is 200×100 and another image is 200×400, I would like for them both to scale in such a way that they take up the same amount of space on the screen.» What does this mean? How will they scale? Will smaller ones scale up and bigger ones scale down to some average? Can you provide a minimal reproducible example of your current markup with a diagram or explanation of how that differs from your desired outcome?

2 Answers 2

I don’t believe you can do this with CSS. While you can calculate square root with CSS in various ways, getting natural dimensions may be problematic. You’d need that in order to find the smallest image.

For a JavaScript solution, you’d have to first establish the smallest image area, then resize each down according to initial proportion, maintaining aspect ratio.

const images = document.querySelectorAll('img'); let smallestArea = 999999999; const getSmallestImageByArea = () => < images.forEach(image => < const width = image.naturalWidth; const height = image.naturalHeight; if (width * height < smallestArea) < smallestArea = width * height; >>); >; const sizeImagesToSmallestArea = () => < images.forEach(image => < let width = image.naturalWidth; let height = image.naturalHeight; const area = width * height; if (area >smallestArea) < const areaRoot = Math.sqrt(area); const proportion = areaRoot / Math.sqrt(smallestArea); const aspectRoot = Math.sqrt(width / height); width = areaRoot / proportion * aspectRoot; height = areaRoot / proportion / aspectRoot; image.style.width = width + 'px'; image.style.height = height + 'px'; >// show hidden images image.style.display = 'inline'; console.log('Initial area:', area, '| Final area:', width * height); >); >; // wait for images: https://stackoverflow.com/a/60949881/1264804 Promise.all(Array.from(document.images) .filter(img => !img.complete) .map(img => new Promise(resolve => < img.onload = img.onerror = resolve; >))).then(() => < getSmallestImageByArea(); sizeImagesToSmallestArea(); >);
/* hide images to prevent jumping effect */ img
     

Источник

Оцените статью