Behavior of img Height and Width Not What I Expected

Hello everyone, I’m still failry new to html/css so I apologize if this is a dumb question, but I’m very confused about the behaviors of / interaction between the width and height properties of images. I’ve got a very basic Fiddle below where everything works as I expect. However:

  1. After removing the height property from html and body, it is clear the image is no longer 50% height of its parent div.
  2. Resizing the window still seems to make width behave exactly as expected, while height seems to do nothing.

So, I’m lost as to why removing a % based height stops making the image scale vertically (even though the parent div also has a % height specified), and why width seems to be responsive while height does not. Any thoughts are appreciated, thank you for reading.

Basic Example that can be modified:

Hi there guyp,

this…

#images > img {
    width: 50%; 
    height: 50%; 
 }

…needs to be…

#images > img {
    width: 50%; 
    height: auto; 
 }

…to maintain the aspect ratio. :winky:

coothead

2 Likes

Hi there guyp,

if, on the other hand, you want the container
and the image to maintain the same ratio,
then you may want something like this…

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<!--<link rel="stylesheet" href="screen.css" media="screen">-->

<style media="screen">
html, body {
    display:table;
    width: 100%;
    height:100%;
    margin: 0;
    background-color: #f0f0f0;
    font:1em/1.62em verdana, arial, helvetica, sans-serif;
 }
body {
    display: table-cell;
    vertical-align: middle;
 }
#images {
    width: 50vw; 
    height: 50vw;
    border: 0.0625em solid #999;
    margin: auto;
    background-color: #fff;
    box-shadow: inset 0 0 3vw #999, 1vw 1vw 1vw #999;
 }
#images  img {
    display: block;
    width: 25vw; 
    height: 25vw; 
    margin: 12.5vw auto;
    box-shadow: 0 0 2vw #666;
}
</style>

</head>
<body> 

<div id="images">
   <img src="http://www.jonathanjeter.com/images/Square_200x200.png" alt="slide">
</div>

</body>
</html>

coothead

If you remove the height from the body then the height of the body is auto and therefore the height:100% you gave to images has nothing to base its height on and resolves to auto also. That then follows that the percentage height you set on the image itself also resolves to auto.

For percentage height to work there needs to be an unbroken chain of heights right back to the root element. Suffice to say that in most cases you do not want to use height:100% in this way.

As others have mentioned above its best to maintain the aspect ratio of the image when resizing and you should set height to auto when changing the width.

2 Likes

"For percentage height to work there needs to be an unbroken chain of heights right back to the root element. "
-Not that I’m blaming you for this, but that just seems like such a weird requirement. Why wouldn’t someone who explicitly specifies width/height at a certain % not want the image at those percents? HTML/CSS seems to have some goofy rules.

Thank you for the example, but I’m not ‘getting it’. When I try to resize the code you provided in Fiddle, the image only changes sizes when ‘moving’ horizontally, vertical shrinking seems to do nothing. Is there no way to specifically control image / element height and width separately outside of Javascript? For example, is container width > height : do this, if not : do that. I suppose Vmin/max does that, but it isn’t as specific as using a % of your container.

If you are happy for the image to bend and stretch and lose its aspect ratio (something you rarely if ever want) you can use vw and vh units, which are like percentages but not as hard to work with.

Using those, you wouldn’t need a height set on the html/body elements:

#images {
  width:100vw; height:100vh;
}

#images > img {
width:50%; height:50%; 
}

You might need to blame the way the universe was constructed :slight_smile:

Beginners always fall foul of height:100% but is a key concept in understanding how css works. When you say height:100% (or any percentage) then what are you actually asking for?

100% of the viewport height?
100% of the document height?
100% of the parent’s containers height?
100% of the viewport height less any scrolling that the element’s position occupies?
100% of a parent’s height whose height is only determined if it has content?

If for example you wanted an image to be 100% height of its container and the containers height is only determined by the height of the image then you have a circular reference that can’t be resolved which is why the parent’s height resorts to auto. That means that for a percentage height to work on the parent then there must be an unbroken chain of
heights back to root.

You can as Ralph suggests use the newer vh units which always give you 100% of the viewport height on which to base your content and then you get a height that is equal to the total height of the viewport (or a percentage of). That again means that say you have an image that is sized at 50% width and 50% height then on a 2500px screen the image will be 1250px wide but if the viewport is only 300px high it will be 150px tall. I don’t think any image will look good at that range.:slight_smile:

It is unlikely as others have already pointed out that this is what you want for an image because an image has an intrinsic aspect ratio related to its width and height. That’s why when you scale an image in one direction (be it height or width) you must set one or the other to auto to allow the image to maintain its correct aspect ratio. If you do not do this the image will be squished or stretched and look ugly (unless its just a random design of colours).

No (good) websites will stretch an image without maintaining its aspect ratio so its not something you would normally need to do although there can be odd exceptions.

It would be silly to resize the image smaller based on the height of a document. A user with a wider monitor who lessened the height of the viewport would see the same small size image as someone on a small device. You would rarely want to scale based on the height unless you are using very large images and then you would set the width to auto. Viewport widths are eventually finite but document heights are almost infinite.

Maybe it would help if you put up a demo of what you want to achieve and we can see why it is causing you problems.

5 Likes

Hello again @PaulOB, sorry it took me so long to get back to this project - thank you for the post. I’ll try to elaborate a bit more and give you some examples (screenshots for the moment since JS Fiddle isn’t working quite the way Chrome/Firefox is right now for me).

I’m trying to keep the entire interface in the browser window without having the person needing to scroll (either direction), while allowing the user to also re-size their window. Because of this, images needs to both re-size themselves based of both height and width too keep themselves as large as possible (with their aspect ratio in tact) without destroying the layout.

Here are a few ‘normal usage’ examples of what I’ve got since I’ve added some Flexbox and Object-Contain/Position into the mix (posting just the links due to image size):
Normal: http://tinypic.com/m/jue1du/1
More Narrow Width: http://tinypic.com/m/jue1dy/1
More Narrow Height: http://tinypic.com/m/jue1e8/1

Though there are some issues still, I can’t figure out how to have the top images (warning, title, data) shrink in a way that keeps the title larger than the other two (haven’t got flexbox shrink working): http://tinypic.com/m/jue1hc/1

Also, (granted this isn’t a huge issue I’m just annoyed by it) I can’t prevent the top images from ‘moving too far down’ when the height is made much smaller: http://tinypic.com/m/jue1hh/1

I admit, between all the html/css options, I’m getting really confused when to use each, and at what point they begin to start conflicting with each other…

*Here is a semi-working JS Fiddle just in case you want to see the actual code:
https://jsfiddle.net/jrj1t3fj/

Unfortunately MCafee blocks me from those links as the site contains dangerous or suspicious content and indeed still managed to spawn unwanted popup windows when blocked! Just attach your images to the post and don’t send people to these dodgy image sharing sites full of dodgy adds and links.:slight_smile:

Virtually impossible and unfeasible due to the nature of the web and not something that should be attempted unless it was part of an admin screen for ‘admin’ desktop users only. How are people going to read your content when it scales that small and how will your content fit in those tiny blocks when the window is small? At the very least you will need multiple scrollbars on each column to accommodate content that overflows when it no longer fits or if users have resized their text.

You shouldn’t be shrinking the layout to fit every screen but indeed for smaller screens you often need larger text because mobiles are hard to read at normal text sizes. You should be re-organising the content as the screen real estate gets bigger or smaller and not simply scaling everything up or down.

Your design looks more or less ok for large screens (but would still need to cater for overflowing content as mentioned above) but for smaller screens you would need to go down to 2 columns and then one column and allow the user to scroll vertically.

On the web you want to avoid setting heights on elements that contain fluid content such as text and in general avoid fixed heights altogether because at some stage that will break.

We’ve already answered that above and you can only scale the image by either giving it a percentage width and leaving its height at auto or by setting its height to a percent (where allowed) and leaving its width at auto. You can’t make choices with css as you would need to use js to determine whether an image should be scaled by its height or by its width depending on available space.

Sorry if the above does not help with your quest but if you can answer the question about how users can use your content when scaled to those small sizes then perhaps we can move forward with a solution :slight_smile: It may be that I misunderstood what I was looking at or your intended uses. Generally blocks of colour without content are just drawings and of little use to me other than as something to work towards.

The web is about ‘content’ and you must have viable content in your mocks up using extravagant data to test the limits of the structures you impose. This needs to be done right at the beginning and not later on in the design as it will soon become apparent what needs to change before you get too deep with a certain approach.

2 Likes

Hello again @PaulOB:

More Important Stuff:
"How are people going to read your content when it scales that small and how will your content fit in those tiny blocks when the window is small? "
-Since the discussion has become much more specific than what I had originally thought it would, I should give you more information (I should have realized that earlier…): The page in question is based around a PC Game, and my expectation is that it will get the most use probably while the user is playing the game (either on a separate monitor or tabbing back and forth). Therefore, I’m only thinking about stand alone monitors/laptop monitors, mobile is of no consequence.

“How are people going to read your content when it scales that small”
-I’ll probably end up enforcing some minimal X/Y restrictions, I’m just trying to give them some flexibility. As far as the questions about elements moving unexpectedly at very small dimensions, that is just for my edification, not practical use.

“We’ve already answered that above and you can only scale the image by either giving it a percentage width and leaving its height at auto or by setting its height to a percent (where allowed) and leaving its width at auto.”
-Is that what “object-fit: contain” is doing ‘behind the scenes’?

“You can’t make choices with css as you would need to use js to determine whether an image should be scaled by its height or by its width depending on available space.”
-Good to know. I’m actually much more comfortable doing things with programming language than html/css (which I have almost no experience in as you could probably tell…).

“Generally blocks of colour without content are just drawings and of little use to me other than as something to work towards.”
-I understand your point, but to me, there isn’t any sense in creating more content in the actual html/css if the basic format isn’t even working. I did make a full Photoshop concept picture, I just can’t for the life of me find it right now. But its essentially what you see now, plus the text, input areas, and checkboxes.

Re-posting of Images:
Normal Size (no problems):

More Narrow Width (still fine, though the middle image at the top “Vind Enh Calc” is about to become an issue as it will become smaller while the other 2 images remain the same size):

More Narrow Height (no problems):

Very Narrow Width (I can’t figure out how to have the top images (warning, title, data) shrink in a way that keeps the title larger than the other two (haven’t got flexbox shrink working) ):

Very Narrow Height: (granted this isn’t a huge issue I’m just annoyed by it) I can’t prevent the top images from ‘moving too far down’ when the height is made much smaller:

Less Important Stuff:
“Unfortunately MCafee blocks me”
-I think the main problem is that you still use MCafee…That said, I do use AdBlock on Chrome and can’t say I’ve ever had any issue with Tiny (or others), nor has anyone else I know.

Yes you should have said that earlier :slight_smile: No worries though at least we got there in the end.

OK fair enough but doesn’t that somewhat make your very wide and very short viewport questions obsolete? If you are going to set a minimum height and width (which would be sensible in this case) then you don’t need to worry about narrow or not very tall viewports and just concentrate on bigger displays.

The problem is that I still don’t know what content you are putting inside those squares or whether when you refer to images you are referring to images of text. e.g.

Why don’t you make those top three elements text instead of images and then you can just set the text size with media queries to match as required. Unless of course you were going to place a more elaborate graphic in there. Why not just place real text on top of a background image if you were looking for a graphic effect.

I can’t see a way that you can have three images at the top and have them scale exactly at the same rate unless you make them all the same size to start with and then they will scale equally.

Or alternatively why bother with three image at all and just make it one image and then it can’t fail to scale uniformly. If you have no text then you have no content so why have multiple images when one will do :slight_smile:

As I said above use text or if it must be an image then make 3 equal size images to start with (or merge into one image) and then they will scale at the same rate (you can just have white space on the image itself).

I would though avoid all the heights you are setting on the containers and let the content dictate the height. You can set a min-height for the page content of 100vh if you wish but then use flexbox (or even display:table-methods although they might be awkward as columns are not aligned) to allow the content to auto fit the height and keep rows even. In that way extravagant situations will not break the layout. Where possible let the content dictate the height of each block as required.

I’m afraid most of this is speculation and may not be of direct help to you but I am trying to guide you in the right direction :slight_smile: What you are designing in not a normal website so some of my concerns may not be an issue for you. I’m just trying to point out the usual pitfalls that we say time and time again on the forums.

If you still had your photoshop mock up of the final product it would be interesting to see exactly what you are aiming for. If it is indeed mostly a graphical interface for special use then you could try as I said above and amalgamate some of the images to aid with uniform scaling.

No object fit merely makes the picture fill the width and the height of the image area that is available while maintaining aspect ratio (depending on which value is being used of course). It does this by increasing the picture width and height uniformly until the image dimensions are fully covered by the image content. Effectively its the same as background-size:cover when used on image backgrounds. This means that the image maintains its aspect ratio but some parts of the image will be invisible and outside the bounds of the tag.

This has nothing to do with how the image tag is scaling because you may have set width to a percent and height to auto, or you may have set height to a percent and width to auto. These will give different results.

I know Mcaffee can be a bit finicky at times and over careful but I have it on 5 computers here and been running it for about 20 years in different forms and rarely have issues with it. It’s a bit of a resource hog at times though. I checked your image link on one of my other computers and that runs ‘Malawarebytes’ and that popped up a warning and blocked the site also. It wasn’t on all your images just a couple so there’s probably a rogue add or a link that goes to a suspicious site. These free image sharing sites are notorious for spreading malware and I wouldn’t touch them with a barge-pole. In these days of really cheap hosting it does pay to have your own little space on the web to share and test.:slight_smile:

Better safe than sorry.

4 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.