amyspark
amyspark

Reputation: 520

Centering flex children without extra space

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

Suppose I've got this layout:

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

The slider is a flex container. The two buttons are inline-block, and I want the slide img to be limited to the viewport's height without extra space.

How can I achieve this?

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

Upvotes: 0

Views: 33

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371251

Maybe something like this will work:

.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

Upvotes: 1

Related Questions