Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CSS to set height of image the same as width

In my project, there are some images. My code looks like:

<div className="col-sm-6">
   <img src="xxx">
</div>
<div className="col-sm-6">
   <img src="xxx">
</div>

The width of img is 100% of div, which is 50% of the whole screen. If I resize the browser, the width of image is changed. In this case, how to keep the height is still the same as width?

like image 696
Benjamin Li Avatar asked Jan 12 '17 03:01

Benjamin Li


1 Answers

It depends on the aspect ratio of the image.

  1. If you want to stretch the image to a square: since the container <div> is 50% of the whole screen. You could've written it as width: 50vw; (50% of the viewport width). The same for your image: width: 50vw; and to keep height the same as the width.:
.col-sm-6 img {
  width: 50vw;
  height: 50vw;
}
  1. If the image is a square, just adjust width. Height will automatically adapt. Since you must be using Bootstrap (guessing from the class name col-sm-6).

  2. If the image is always panoramic:

.container {
  width: 50vw;
  height: 50vw;
  border: 1px solid lime;
  overflow: hidden;
}

.container img {
  height: 100%;
  min-width: 100%;
}
<div class="container">
  <img src="http://www.w3schools.com/css/img_lights.jpg">
</div>
  1. Same logic above for always vertical images.
like image 55
warkentien2 Avatar answered Nov 15 '22 05:11

warkentien2