0

Below is my div structure. #myMenu height is dynamic. How do I make the images fit maintaining its aspect ratio when #myMenu's height is changed?

This is the expected result:

enter image description here

<div id="myMenu">
    <div class="col col20">
       <div class="gents"></div>
   </div>
   <div class="col col20">
       <div class="gents"></div>
   </div>
   <div class="col col20">
       <div class="gents"></div>
   </div>
   <div id="other" class="col40"> 
       <div class="gents"></div>
   </div>
</div>

css:

#myMenu{
    background-color: #f00;
    height: 300px; /*this value is dynamic*/
    padding:0;
    margin:0;
}
.gents{
    width:100%;
    padding-bottom:100%;
    background-size:cover;
    background-image: url(http://img42.com/9WM6f+);
}
.col{
    width: 200px;
    border:1px solid yellow;
}

.col20{
    height:20%;
}
.col40{
    height:40%;
}

Here is a Fiddle

Becky
  • 5,467
  • 9
  • 40
  • 73
  • 1
    can you use `img` tag http://jsfiddle.net/victor_007/4bx0vab1/ i this example i have only added the `width` – Vitorino fernandes May 02 '15 at 10:52
  • @0_o thanks and yes, if that would help to get the expected result. – Becky May 02 '15 at 10:53
  • I agree with using `img` tag. It's hard to keep the aspect ratio of something that really doesn't have a set dimension. – DigitalDouble May 02 '15 at 10:54
  • Is something like this useful: http://jsfiddle.net/ufrbhagx ? I added another `div` to see how it reacts, however, the `img` suggestion could work too. – ShastriH May 02 '15 at 10:56
  • @DigitalDouble thanks for your input. That gives more confidence in using 0_o answer using `` :) – Becky May 02 '15 at 10:58
  • Well thanks to your question as it got me curious and has lead me to this: http://stackoverflow.com/questions/1495407/css-maintain-div-aspect-ratio. It's possible but it just needs a bit of math. :P – DigitalDouble May 02 '15 at 11:03

1 Answers1

0

demo - http://jsfiddle.net/victor_007/4bx0vab1/

you can use a <img> tag

Vitorino fernandes
  • 15,794
  • 3
  • 20
  • 39