流体容器中包含的流体图像

时间:2015-09-24 22:28:25

标签: html css

我有一个具有最大高度和宽度约束的图像包装器(在此示例中为300x200),我正在尝试将流体图像放置在容器内,以满足这些约束。

图像的宽度按预期缩放,但图像的高度始终超出父div。什么是使用CSS单独适当缩放此图像的正确方法?

.container {
  max-width: 500px;
  overflow: hidden;
  background-color: #eef;
  margin: 0 auto;
}

.figure-image-wrapper {
  max-width: 300px;
  max-height: 200px;
  margin: 0 auto;
}

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

.figure-caption {
  text-align: center;
}
<div class="container">
  <figure class="figure">
    <div class="figure-image-wrapper">
      <img src="//placehold.it/700x700" class="figure-image"/>
    </div>
    <figcaption class="figure-caption">This is my caption. It's expect to span beyond the width of the image. The image above should scale within a 300x200 .figure-image-wrapper</figcaption>
  </figure>    
</div>

2 个答案:

答案 0 :(得分:0)

这应该适合你:

.figure-image-wrapper {
    max-width: 300px;
    max-height: 200px;
    margin: 0 auto;
    text-align: center;
}

.figure-image {
    max-width: inherit;
    max-height: inherit;
}

DEMO

答案 1 :(得分:0)

AHAH!诀窍是只从父包装继承图像的max-height

.container {
  max-width: 500px;
  overflow: hidden;
  background-color: #eef;
  margin: 0 auto;
}

.figure-image-wrapper {
  max-width: 300px;
  max-height: 200px;
  margin: 0 auto;
  text-align: center; /* Added: Center the image */
}

.figure-image {
  max-width: 100%;
  /* Removed: height: auto; */
  max-height: inherit; /* Added */
}

.figure-caption {
  text-align: center;
}
<div class="container">
  <figure class="figure">
    <div class="figure-image-wrapper">
      <img src="//placehold.it/700x700" class="figure-image"/>
    </div>
    <figcaption class="figure-caption">This is my caption. It's expect to span beyond the width of the image. The image above should scale within a 300x200 .figure-image-wrapper</figcaption>
  </figure>    
</div>