Css scaling image in div

How do I fit an image (img) inside a div and keep the aspect ratio?

I have a 48×48 div and inside it there is an img element, I want to fit it into the div without losing any part, in the mean time the ratio is kept, is it achievable using html and css?

13 Answers 13

Use max-height:100%; max-width:100%; for the image inside the div.

@ZoveGames Non-JS enabled browsers? Yahoo stats from 2010 show a 1.3% average. I think it’s safe to assumed that a. it’s probably lower today and b. programmers.stackexchange.com/questions/26179/…

It does not work for me. It makes the image 100% of it’s own size (eg.: 300px wide for an image that actually is 300px wide).

There is some awful Chrome-on-Windows specific bug that this causes. Potentially some bad interaction with certain smoothscroll plugins I have. It ends up trying to scroll the body even though the mouse is over a overflow:scroll div with a large image in it. Curious. Even more strange: Max’s solution actually fixes it. I’m quite fed up with CSS, really. Used to be powerful and cool. Now implementations just produce buggy inconsistency after buggy inconsistency.

only works when scaling down an image. if you want to fit a small image in a bigger container, this won’t work

Читайте также:  Php mail auth login

CSS Object-fit

Unfortunately max-width + max-height do not fully cover my task. So I have found another solution:

To save the Image ratio while scaling you also can use object-fit CSS3 propperty.

Bad news: IE not supported (Can I Use)

If you want the image to be in the top left rather than centered, you also need to use object-position 0 0.

This is the only answer that worked for me to create a responsive image background that filled the screen while maintaining the image aspect ratio.

You will need some JavaScript to prevent cropping if you don’t know the dimension of the image at the time you’re writing the css.

HTML & JavaScript

 
Css scaling image in div

CSS

If you use a JavaScript Library you might want to take advantage of it.

Michael’s answer is much simpler and it doesn’t use Javascript. I don’t know about browser compatibility though.

No, Michael’s answer works as long as the image is bigger than the div. If you want the image to fill the div regarding of image size (and, if you don’t know the image size in advance, you do), this is the way to go.

Could you not use max-height:100%; max-width:100%; min-width:100%; min-height:100% and get the same result then? Honest question.

No, by doing that you force the width and height to be be 100%, so you change the image aspect ratio.

onload won’t be called when the image is cached in the browser, so this will only work when the image is loaded for the first time.

HTML

CSS

This will make the image expand to fill its parent, of which its size is set in the div CSS.

I was having a lot of problems to get this working, every single solution I found didn’t seem to work.

I realized that I had to set the div display to flex, so basically this is my CSS:

For your example.. I believe you are looking for something like on your image CSS: height: auto; width: 100%;

the task was to fit image into a div, it implies that div has the dimensions and the image has only aspect ratio. I need to set height to some value, otherwise the question conditions will be distorted as well as my image. Please have a look at JS fiddle and change what you think is needed to make it work. Thanks.

For me, the following CSS worked (tested in Chrome, Firefox and Safari).

There are multiple things working together:

  • max-height: 100%; , max-width: 100%; and height: auto; , width: auto; make the img scale to whichever dimension first reaches 100% while keeping the aspect ratio
  • position: relative; in the container and position: absolute; in the child together with top: 50%; and left: 50%; center the top left corner of the img in the container
  • transform: translate(-50%, -50%); moves the img back to the left and top by half its size, thus centering the img in the container

Super late but, try this solution:

Setting the photo as a background image will give us more control over size and placement, leaving the img tag to serve a different purpose.

Below, if we want the div to be the same aspect ratio as the photo, then placeholder.png is a small transparent image with the same aspect ratio as photo.jpg. If the photo is a square, it’s a 1px x 1px placeholder, if the photo is a video thumbnail, it’s a 16×9 placeholder, etc.

Specific to the question, use a 1×1 placeholder to maintain the div’s square ratio, with a background image using background-size to maintain the photo’s aspect ratio.

I used background-position: center center; so the photo will be centered in the div. (Aligning the photo in the vertical center or bottom would get ugly with the photo in the img tag.)

div < background: url(photo.jpg) center center no-repeat; background-size: contain; width: 48px; // or a % in responsive layout >img < width: 100%; >

Источник

Scaling Images Proportionally in CSS with Max-width

Right now, I’m using max-width to scale images to fit. However, they don’t scale proportionally. Is there a way to cause this to happen? I’m open to Javascript/jQuery. If possible, is there a way to do this without knowing the original dimensions of the image (maybe determine this using Javascript/jQuery)?

8 Answers 8

Contrary to the accepted answer, you can do this without specifying the size in the HTML. It can all be done in CSS:

Please upvote this answer instead of the accepted one. This is more correct, cause you actually DON’T need to set width/height of the image in HTML. Pure CSS works just fine.

Appears a solution (from having key ‘height: auto;’ ) . well at least SOME TIMES AS/BUT What’s the reason the ‘width: ..’? —indeed as I guessed I found that not needed (in my 1 test, in both Chrome & Firefox) plus 2 other reasonably-voted up answers here, #answer-2077065 & #answer-23001224 , don’t do that & 2nd solution even says ‘Don’t set your width..’ telling that’s problems; but STILL this answer doesn’t tell why it does that, so I just down-voted this answer esp as it’s gotten so many up-votes (now still 62) its seemingly (big) mis-ranked over those other 2 answers with max 9 votes.

You need to specify the original width and height:

And then use something like this in the CSS:

You could try this with jQuery if you don’t have the width and height up front, but your mileage may vary:

Obviously replace #content with whatever selector you want to scope the functionality to.

You dont need the original dimensions (though it is a good practise to add them to the img tag).. jsfiddle.net/PYxYv

I’d like to point out. I’m sure this works but Chris Redford’s answer below was simple and effective.

With this solution then a slow-loading image will change the page layout when it finally loads. Depending on the image and where it is on the page, this can be horrible for usability. I’m sure we’ve all used sites where the page «jumps» just as you’re about to click on a link because a banner ad loaded that didn’t have an initial height set — it’s incredibly annoying. If anyone has a solution that allows you to set an initial height and have the image retain aspect-ratio when resized by a max-width, then I’d be glad to hear it.

when setting up constant width use:

Here’s how to do it with no Javascript. Set your max-width to the length you want.

This worked for me tested on a Mac with Firefox 28, Chrome 34 and Safari 7 when I had no width or height settings explicitly set in the img tags.

Don’t set your width in CSS to 100% after the max-width setting as one person suggested because then any images that are narrower than the width of the container (like icons) will be blown up much larger than desired.

hopefully it is not too late , but with this pease of code i managed to get proportional images in my gallery. it will take time to understand what is going on but try it and enjoy.

Using both width and max-width on the image screw up IE8.

Put the width on your image and wrap it in a div that has the max-width. (Then curse MS.)

I had to do this with the following requirements:

  1. Page must not get reflown when images load. The image sizes are known on the server side and calculations can be made.
  2. Images must scale proportionally
  3. Images must not be wider than the containing element
  4. Images must not be scaled up, only down when necessary
  5. Must use an img element and not a background to make sure the images also print properly
  6. No JavaScript!

The closest I came up with is this terrible contraption. It requires three elements and two inline styles, but as far as I know this is the best way to scale images proportionally. All the height: auto; suggestions here negate the point of specifying the image dimensions on the server side and cause the content to jump around while loading.

.image < position: relative; >.image img < position: absolute; top: 0; left: 0; width: 100%; height: 100%; >  

Источник

I am trying to scale an image to 100% width of the div it is contained within (it is a responsive layout with the div changing size depending on window size, hence the need to scale the images). This is my css:

.container < width: 200px; height: 200px; overflow: hidden; position: relative; margin: 10px; float: left; >@media (max-width: 520px) < .container < width: 100px; height: 100px; margin: 5px; >> .container img

Image links remain at their full size of 200px rather than scaling down to 100% of the div which is 100px. Anyone know how I can get the linked images to scale?

Your code seems to work OK for me already. When the window width is less than 520px the image shrinks to 100x100px. Can you make a demo of the problem please?

@andyb You guys are right, this code seems to work so there must be something else getting in the way. I simplified it when I posted the question on here. I can’t find what’s causing the problem in my original files. I’ve uploaded a test version of the site here: andreaalice.com/test You’ll see it’s the first image that doesn’t scale. The problem is with .element div.

3 Answers 3

I made a quick example that seems to do what you need here.

Yes @Robyflc this would be the correct answer in other circumstances, however I had other things in my code that prevented this from working, namely position:aboslute set on my container.

@user2419684 In the code you posted you have a position:relative set to the container. Did you change it to absolute after posting??

@Robyflc the code I posted was a simplified version of the issue I was having, rather than posting the code for my entire site. So the code I posted actually ended up working fine — and after uploading my entire site andyb discovered the problem was elsewhere in position: absolute on my selected elements as seen in the answer below.

I managed to recreate the problem in a simple demo. Just shrink the results window to < 520px and the images should resize but the first one does not.

The problem seems to be the following rule

Removing the position:absolute; fixes the problem. I think this is because the surrounding on the first image has no width . Adding

fixes the problem when page width < 520px but that then breaks page with >= 520px! So I’d just recommend removing position:absolute unless you need that for any other reason. It doesn’t seem to affect anything else on the page as far as I can see.

Lastly (and it’s only minor) but all the tags should really be self-closing. The page nearly validates.

You seem to have discovered the issue, however if I remove position:absolute I lose all the hover effects on the elements. I think I’ve found another solution — not sure whether it’s the best. I’ve taken the link off the images and instead created a separate link with a class to fill 100% of the div, and z-index:1 . It also solves another problem I discovered: previously the text in my elements wasn’t clickable because it was sitting in front of the images. Updated code is here: andreaalice.com/test

@Robyflc please don’t try to get get attention from commenting on other answers. Please comment on the question in future.

@user2419684 Yes, I missed the hover part. I was only checking for fixing the resizing, sorry It looks like you’ve solved it another way now anyway, so well done! 🙂

@Robyflc There are still rules and best practice to follow. Your comment was wrongly placed for whatever reason which I was simply pointing out.

Источник

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