Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force image to maintain native height when width changes

Tags:

html

css

image

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="">
like image 350
Adam Pietrasiak Avatar asked Jan 21 '16 18:01

Adam Pietrasiak


People also ask

How do I resize an image using CSS without losing the aspect ratio?

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.

How do I set the width and height of an image responsive?

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.

What will happen if width and height of the image is not specified?

If width and height are not specified, the page will flicker while the image loads.

How do I lock aspect ratio in HTML?

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.


1 Answers

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

like image 121
isherwood Avatar answered Oct 18 '22 20:10

isherwood