I have some text and an image floating to the right that looks like this :
The HTML looks like this :
<body>
<div id="container">
<div id="img"/>
<p>
What is Lorem Ipsum?..... etc
</p>
</div>
</body>
and the CSS that is placing the image looks like this :
#img {
background-image: url('http://www.w3.org/2008/site/images/logo-w3c-screen-lg');
background-size: 100%;
background-repeat: no-repeat;
background-position: top;
height: 140px;
width: 250px;
float: right;
}
When I make the screen smaller I would like the image to scale as well. I dont want it squeezing the text on the left. If I make the screen smaller then this is what it looks like :
So I try and use percentages instead of absolute values.
Unfortunately if I use percentages in my CSS I get nothing. See below :
#img {
background-image: url('http://www.w3.org/2008/site/images/logo-w3c-screen-lg');
background-size: 100%;
background-repeat: no-repeat;
background-position: top;
height: 30%;
min-height: 30%;
width: 30%;
min-width: 30%;
float: right;
}
How do I get my image to scale properly when I resize my browser?
4
Answers
Thanks for everyones tips.
I found my own way of solving this by using viewport width and aspect ratio.
If I specify the width as always being a percentage of the screen width (vw) then the image will proportionally resize when making the screen smaller.
You need to define some kind of height as well, but if you use vh, or some other kind of height attribute then you get weird results. If you use aspect-ratio 2/1 or whatever the dimensions of the image are, then that takes care of height and preserves the ratio.
https://playcode.io/1141029
If you set the height and width with percentages and the min values with pixels it works just fine.
Not sure if this is how you wanted it to be
playcode
I just updated your sample like this
html:
playcode
You could consider, making it a flex display on smaller devices, so that the text wraps after the image. Not sure, if this is what you’re looking for, but it might improve user experience for smaller devices, otherwise the image may become too small to view and the text difficult to read.
Furthermore, this seems to be one of the valid use cases for the otherwise not outdated, but rather old fashioned layouts. I haven’t seen floats recently. I suppose I tend to stay away from them.
Hope this helps.