https://jsfiddle.net/q97jn9jp/
I've got some image, but I don't know it's width
or height
. I want it to be 100%
wide, but I want it's height to stay natural (if image height was 100px
I want it always to stay 100px
).
Is that possible?
I don't want to use javascript.
img {
width: 100%;
//height: ???;
}
<img src="https://placehold.it/100x100" alt="">
The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.
To make an image responsive, you need to give a new value to its width property. Then the height of the image will adjust itself automatically. The important thing to know is that you should always use relative units for the width property like percentage, rather than absolute ones like pixels.
If width and height are not specified, the page will flicker while the image loads.
In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.
I realize that the goal here is to not have to use image-specific styling. If this limitation only applies to dimensions, though, this might work:
.stretchy {
background-image: url(https://placehold.it/100x100);
background-size: 100% 100%;
}
.stretchy img {
display: block; /* eliminates descender space inherent with inline elements */
visibility: hidden;
}
<div class="stretchy">
<img src="https://placehold.it/100x100" alt="">
</div>
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With