首页 > 解决方案 > 将两个图像放在一个 flex-box 容器中

问题描述

我有两张图片我想放在彼此的顶部,例如一个产品(内部)和一个“折扣”横幅(外部)。

目前,我在a-tag 中有图像,其中a-tag 是一个 flex-box 容器,因此我可以使用align-itemsand justify-content

我的 HTML 如下

.image-wrapper {
    height: 50%;
    margin-top:20px;
    flex-grow: 1;
}

.image-wrapper a{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
}

.image-wrapper img{
    width: auto;
    max-height: 100%;
}
<div class="image-wrapper">

      <a href="{{p.link}}" target="_blank" rel="noopener">
        <img src="https://lh3.googleusercontent.com/proxy/9R1yfiOspfOVdrip4b4kF5i1cCaJWmdyKRJbtXw6bnmXiPqYRLZyUYYJL3MwiRWay8JjDNmdT8cpgxB7pBgWdLz04s6mjEYDE-DD5btDasFt7j-KPraA0YIFiF2rN2kSq9uq0PYNHc46NVmEokNuc1GbhujtP_NKyg72rnM" alt="Image of product" /></a>
      
      <img src="https://lh3.googleusercontent.com/proxy/9R1yfiOspfOVdrip4b4kF5i1cCaJWmdyKRJbtXw6bnmXiPqYRLZyUYYJL3MwiRWay8JjDNmdT8cpgxB7pBgWdLz04s6mjEYDE-DD5btDasFt7j-KPraA0YIFiF2rN2kSq9uq0PYNHc46NVmEokNuc1GbhujtP_NKyg72rnM" alt="Discount-banner" />

</div>

我希望仍然在 a-tag 中保留图像,但如果不能这样做,那很好(首要任务是将两个图像放在彼此之上)

标签: htmlcss

解决方案


要将第二个图像覆盖在第一个图像上,您可以使用position: absolute

.image-wrapper {
  height: 50%;
  margin-top: 20px;
  flex-grow: 1;
}

.image-wrapper a {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.image-wrapper img {
  width: auto;
  max-height: 100%;
}

.image-wrapper .overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="image-wrapper">

  <a href="{{p.link}}" target="_blank" rel="noopener">
    <img src="http://placekitten.com/300/300" alt="Image of product" />
    <img class="overlay" src="http://placekitten.com/100/100" alt="Discount-banner" />
  </a>
</div>


推荐阅读