在响应式容器内使图像高度响应

时间:2017-12-10 15:16:40

标签: javascript html css

当我调整宽度时,我有一个响应式图像,但是当我调整高度时,我得到一个滚动条。如何使它在高度响应? 没有制作背景图片?

enter image description here

1 个答案:

答案 0 :(得分:2)

你可以这样做:

* {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>

重点是从max-height: 100vh元素的已定义img中扣除兄弟和其他影响元素的定义高度。任何定位也必须考虑在内。没有别的方法可以做到。