1

I have a div wrapping two images. I want the second image to fit within the div because the width and height are dynamic.

My code looks like this:

.box {
  width: 640px;
  height: 540px;
  float: left;
  overflow: hidden;
}

.img-border {
  width: 100%;
  height: 100%;
  display: block;
  border-radius: 20px;
  margin: 5px;
}
<div class="box" id="target">
  <div align="center">
    <img src="http://cdn.tgdd.vn/Files/2014/06/24/551004/game-duoi-hinh-bat-chu4.jpg" width="60%" height="60%">
  </div>
  <img class="img-border" id="imgQues" src="https://4.bp.blogspot.com/-K5SwATiq6cI/U84bk7MZPWI/AAAAAAAADkI/4lWV0ErVAFs/s1600/2014-07-22+14.11.00-1.png" />
  <div class="comment" id="chatbox">
  </div>
</div>

The problem you can see at .img-border is not fitting (stretch and resize) into .box div and keeping its aspect ratio.

Is there any method to fit the second image img-border in div and keep ratio?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Ave
  • 4,338
  • 4
  • 40
  • 67

1 Answers1

1

try the following:

.box {
  width: 640px;
  height: 540px;
  float: left;
  overflow: hidden;
  /**
    Just for visualization 
  **/
  background: gray;
}

/**
  Just dummy names, rename as you like
*/
.box__first-child,
.box__second-child {
  float: left;
  width: 49.99999999%;
}

/**
  Force images to always take remaining space
*/
.box img {
  width: 100%;
}

.img-border {
  width: 100%;
  height: 100%;
  display: block;
  border-radius: 20px;
  margin: 5px;
}
<div class="box" id="target">
  <div class="box__first-child" align="center">
    <img src="http://cdn.tgdd.vn/Files/2014/06/24/551004/game-duoi-hinh-bat-chu4.jpg" width="60%" height="60%">
  </div>
  <div class="box__second-child">
    <img class="img-border" id="imgQues" src="https://4.bp.blogspot.com/-K5SwATiq6cI/U84bk7MZPWI/AAAAAAAADkI/4lWV0ErVAFs/s1600/2014-07-22+14.11.00-1.png" />
    <div class="comment" id="chatbox">
    </div>
  </div>
</div>

The html changes are not mandatory, you can do it in another way too, but this seems to be the cleanest for me. The trick basically is to force the images to always take up full space and align the items after each other with float.

Edit:

Preview Variant 1

jsfiddle - variant 1

Preview Variant 2

jsfiddle - variant 2

Timo Reymann
  • 755
  • 5
  • 16
  • 1
    It should be two different row. Your example, two images in the same line. I want to first image should have 1/3 at top of div, the second image should be 2/3 on the bottom. – Ave Sep 15 '18 at 15:10
  • @vanloc I added both variants i think you could mean ... sry i am not so good at this :D – Timo Reymann Sep 17 '18 at 19:45