基于高度、垂直对齐、基于百分比的img使用display:table/table单元格



我正在创建一个众所周知的媒体对象的变体,它符合以下标准:

  • Container元素具有显式高度集
  • 所有儿童的身高应以百分比为基础
  • 图像元素应能够垂直对齐

我使用的是古老的display: table/table-cell方法:

<div class="o-media">
  <div class="o-media__img">
    <!-- begin picture component -->
    <div class="c-picture">
      <div class="c-picture__container">
        <picture class="c-picture__el">
          <source media="(min-width: 1024px)" srcset="https://www.topoutshoes.com/media/catalog/product/cache/1/image/1200x1200/9df78eab33525d08d6e5fb8d27136e95/_/1/_11_1_7.jpg" class="c-picture__source">
          <img src="http://shopshoeguru.com/sites/default/files/image/shoeguru-banner-red.png" class="c-picture__img _o-media__image--overview-01" alt="Overview 1 photo">
        </picture>
      </div>
    </div>
    <!-- end picture component -->
  </div>
  <div class="o-media__body">
    <!-- some copy and such -->
  </div>
</div>

和CSS:

* {
  border: 1px solid red;
}
.o-media {
  height: 550px;
}
  .o-media__body {
    height: 50%;
  }
  .o-media__img {
    height: 50%;
  }
  ._o-media__image--overview-01 {
    /* want to be able to set this using percentage! */
    height: 200px;
  }
.c-picture {
  display: table;
  width: 100%;
  height: 100%;
}
  .c-picture__container {
    display: table-cell;
    vertical-align: middle;
  }
  .c-picture__el {
    display: inline-block;
  }
  .c-picture__source {
    display: none;
  }
  .c-picture__img {
    display: block;
  }

下面是这段代码的实际操作:https://jsfiddle.net/v9gf3c9a/

正如我在CSS中的评论所指出的,问题是我必须明确设置img的高度,因为由于使用了display: tabledisplay: table-cell,它不尊重基于百分比的高度。如果我使用常规的旧display值,如blockinline-block,则img上的百分比可以正常工作。

有没有什么方法可以实现这一点,这样我就可以在img上使用百分比,但仍然可以通过display: table/table-cell使用vertical-align

这个怎么样:

* {
  border: 1px solid red;
}
.o-media {
  height: 550px;
}
  .o-media__body {
    height: 50%;
  }
  .o-media__img {
    height: 50%;
  }
  ._o-media__image--overview-01 {
    /* want to be able to set this using percentage! */
    height: 100%;
    position: absolute;
  }
.c-picture {
  display: table;
  width: 100%;
  height: 100%;
}
  .c-picture__container {
    display: table-cell;
    vertical-align: middle;
    height: 100%;
  }
  .c-picture__el {
    display: inline-block;
    position: relative;
    height: 80%;
  }
  .c-picture__source {
    display: none;
  }
  .c-picture__img {
    display: block;
    height: 100%;
  }

或者,您可以使用flexbox,在flex容器上使用align-items: center;

最新更新