在<figure>中的高度和宽度的响应图像

时间:2017-04-18 15:12:21

标签: html css

我在<figure>内有一张图片。我希望在调整窗口大小时,图像具有响应行为,我希望始终能够观察图像高度和宽度的100%。我希望永远能看到整个图像。

http://jsfiddle.net/ckdm0joj/

figure.figure_container {
  position: relative;
  width: 100%;
  max-height: 250px;
  border-radius: 6px;
  -moz-border-radius: 6px;
  -webkit-border-radius: 9px;
  overflow: hidden;
  margin-top: 10px;
  margin: 0 auto;
}

.figure_container img {
  width: 100%;
}
<figure class='figure_container'>
  <img src='https://lumiere-a.akamaihd.net/v1/images/dory_characters_0afa6e45.jpeg?region=0%2C0%2C1200%2C778' />
</figure>

2 个答案:

答案 0 :(得分:0)

是的,你可以做到。

将以下CSS替换为:

.figure_container img{
  max-width: 100%;
  max-height: inherit;
  width: auto;
}

通过将inherit添加到max-height属性,您可以告诉CSS不要使图像比其父元素更高。因此,如果您将.figure-container高度更改为350px,则图片的max-height也将为350px

  

inherit关键字指定属性应继承其值   来自其父元素。

在阅读您的评论后编辑:

如果您希望其容器的完整widthwidth: auto替换为width: 100%。但是,这会拉伸您的图片,因为.figure-container的{​​{1}} max-width

250px

&#13;
&#13;
.figure_container img{
    max-width: 100%;
    max-height: inherit;
    width: 100%;
}
&#13;
figure.figure_container{
    position: relative;
    width: 100%;
    max-height: 250px;
    border-radius: 6px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 9px;
    overflow: hidden;
    margin-top: 10px;
    margin: 0 auto;
}

.figure_container img{
  max-width: 100%;
  max-height: inherit;
  width: 100%;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果你不介意看到你的图像被拉伸,那么flex就是这样:http://jsfiddle.net/ckdm0joj/2/

figure {
  display:flex;
  max-height:250px;
  border-radius:6px;
  overflow:hidden;
  width:100%;
  margin:0;
  padding:0
}
img {
  flex:1;
}
body {
margin:0;
}
<figure class='figure_container'>
  <img src='https://lumiere-a.akamaihd.net/v1/images/dory_characters_0afa6e45.jpeg?region=0%2C0%2C1200%2C778' />
</figure>