使flex儿童居中,无需额外空间

时间:2018-11-17 12:43:23

标签: html css css3 flexbox

MWE: https://jsfiddle.net/zjgc9dfx/

假设我有这个布局:

<div class="slider">
  <span>button here</span>
    <div class="slide">
      <img src="https://loremflickr.com/1000/1000" alt="Bacn">
    </div>
  <span>button here</span>
</div>

slider是一个伸缩容器。这两个按钮是inline-block,我希望将slide img限制为视口的高度,而没有多余的空间。

我该如何实现?

* {
  margin: 0;
  padding: 0;
}

.slider {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: red;
}

.slider .slide img {
  width: 100%;
  max-height: 100%;
}
<div class="slider">
  <span>asd</span>
  <div class="slide">
    <img src="https://loremflickr.com/1000/1000" alt="Bacn">
  </div>
  <span>asd</span>
</div>

1 个答案:

答案 0 :(得分:1)

也许这样可以工作:

.slider {
  display: flex;
  align-items: center;
  height: 100vh;
  background-color: red;
}

.slider>span {
  flex-shrink: 0;    /* disables shrinking feature */
}

.slider>.slide {
  flex: 1;          /* consume all free space */
  height: 100%;
}

.slider .slide img {
  width: 100%;
  max-height: 100%;
  object-fit: cover;
  vertical-align: bottom;    /* https://stackoverflow.com/a/31445364/3597276 */
}

* {
  margin: 0;
  padding: 0;
}
<div class="slider">
  <span>button here</span>
  <div class="slide">
    <img src="https://loremflickr.com/1000/1000" alt="Bacn">
  </div>
  <span>button here</span>
</div>

jsFiddle demo