Skip to content
Advertisement

Image max height and max width while preserving aspect ratio

Is it possible to give max-height and max-width to an image while preserving aspect ratio without using js?

For example, I want an image to be with a height of 38px and the width auto. If the width is higher than 200px, I want the width to be 200px and the height auto.

If it’s not possible without js, does anyone have an idea how to do it with js and without resizing the image after it’s already loaded?

Advertisement

Answer

You can nest the image in a 200×38 container, then set the max-width and max-height of the image to 100%. Here is a working snippet (I have included JS to make it interactive, but it is not necessary. Try resizing the container using the sliders):

var width = document.getElementById("width");
var height = document.getElementById("height");

var widthInput = document.getElementById("widthInput");
var heightInput = document.getElementById("heightInput");

var imageContainer = document.querySelector("div");

widthInput.addEventListener("input", function() {
  width.innerHTML = this.value + "px";
  imageContainer.style.width = this.value + "px";
});

heightInput.addEventListener("input", function() {
  height.innerHTML = this.value + "px";
  imageContainer.style.height = this.value + "px";
});
div {
  width:  200px;
  height: 200px;
  border: 1px dashed #000;
}

.image {
  display:    block;
  max-width:  100%;
  max-height: 100%;
  background: #333;
}
<div>
  <img class="image" src="https://via.placeholder.com/400"/>
</div>

<br/>

<label>Width: <span id="width">200px</span></label>
<br/>
<input id="widthInput" type="range" min="0" max="400"/>
<br/>
<label>Height: <span id="height">200px</span></label>
<br/>
<input id="heightInput" type="range" min="0" max="400"/>

You can notice that however you change the dimensions of the container, the image is still contained within it. By setting the container to 200px wide by 38px tall, you can force the image to stay within the limits 0px ≤ width ≤ 200px and 0px ≤ height ≤ 38px.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement