首页 > 解决方案 > 设置 img 父级的高度会破坏 flex align-items 和 text-align

问题描述

我有一个拍卖应用程序,其中列表显示在右侧,图像和文本描述。我希望.imgmax-heightmax-width90%Max-width有效,但为了让 max-height 工作,我必须设置.img's 包含块 ( .a_img) 的高度。一旦我这样做了, .image 的align-items: center;andtext-align: center;声明就不再起作用了。发生了什么事,我该如何解决这个问题?谢谢你。

.listings {
    display: flex;
    margin-bottom: 1rem;
    height: 116.8px;
}

.image {
    flex: 1.2;
    display: flex;
    align-items: center;
    text-align: center;
    max-height: 100%;
}

.text {
    flex: 2;
}

.img {
    max-height: 90%;
    max-width: 90%;
}

.a_img {
    height: 100%;
}
<div class="listings">
    <div class="image">
        <a class="a_img" href="www.google.com">
            <img class="img" src="https://cdn.shopify.com/s/files/1/2660/5202/products/shopify-image_0c6f7a25-f7ae-409f-a89b-df63d9c7b463_1400x.jpg?v=1586379733" alt="Product Image">
        </a>
    </div>
    <div class="text">
        some text<br>some text<br>some text<br>some text
    </div>
</div>

标签: htmlcssflexbox

解决方案


您可以简单地将其替换max-heightheighton .image,然后将您想要的所有内容更改为预期的输出,如下所示

.listings {
  display: flex;
  margin-bottom: 1rem;
  height: 116.8px;
}

.image {
  /*flex: 1;*/
  /* altered */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  height: 100%;
  /* altered */
}

.text {
  flex: 1;
}

.img {
  max-height: 90%;
  max-width: 90%;
}

.a_img {
  height: 100%;
}
<div class="listings">
  <div class="image">
    <a class="a_img" href="www.google.com">
      <img class="img" src="https://cdn.shopify.com/s/files/1/2660/5202/products/shopify-image_0c6f7a25-f7ae-409f-a89b-df63d9c7b463_1400x.jpg?v=1586379733" alt="Product Image">
    </a>
  </div>
  <div class="text">
    some text<br>some text<br>some text<br>some text
  </div>
</div>


推荐阅读