paraplu
paraplu

Reputation: 261

Make Image Height responsive inside responsive container

I have a responsive image when I adjust width, but when I adjust height I get a scrollbar. How to make it responsive in a height as well? without making it background image?

enter image description here

Upvotes: 0

Views: 90

Answers (1)

VXp
VXp

Reputation: 12118

You can do it like this:

* {margin:0;padding:0;box-sizing:border-box} /* recommended */

html, body { /* modified */
  width: 100%;
  height: 100%;
  background: #000;
}

.container {
  position: fixed;
  bottom: 20px;
  left: 20px;
}

.menu {
  position: relative;
  /*max-height: calc(100vh - 50px);*/
  /*max-width: 100vw;*/
  background: #fff;
  overflow: auto;
  border: 2px solid black;
}

ul {
  display: flex;
  /*width: 100%;*/
  height: 40px; /* needs to be defined / adjust to your needs */
  list-style-type: none;
  padding: 0 0 10px 0;
  /*margin: 0;*/
}

li {
  display: flex; /* added */
  justify-content: center; /* added */
  align-items: center; /* added */
  flex: 1; /* modified */
  /*text-align: center;*/
  padding: 10px 0;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.2);
}

li:hover {
  /*flex: 1 1 100%;*/
  /*text-align: center; already used */
  /*padding: 10px 0; already used */
  /*cursor: pointer; already used */
  background: rgba(0, 0, 0, 0.1);
}

img {
  display: block; /* recommended / removes the bottom margin/whitespace */
  max-width: 100%; /* modified / recommended: use images which are 350px (or whatever you want) wide by default */
  max-height: calc(100vh - 60px); /* mandatory / - the defined height of the ul which is 40px - bottom: 20px */
}
<div class="container">
  <div class="menu">
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <div>
      <img src="http://3.bp.blogspot.com/_EqZzf-l7OCg/TNmdtcyGBZI/AAAAAAAAAD8/KD5Y23c24go/s1600/homer-simpson-1280x1024.jpg" alt="">
    </div>
  </div>
</div>

The point is to deduct the defined heights of sibling and other affecting elements from the defined max-height: 100vh for the img element. Any positioning must also be taken into account. There is no other way of doing it.

Upvotes: 2

Related Questions