【问题标题】:Proportional image scale (width & height) to contain inside responsive DIV包含在响应式 DIV 中的比例图像比例(宽度和高度)
【发布时间】:2016-03-14 21:04:44
【问题描述】:

我有一个响应式 DIV,它设置为浏览器宽度 (100%) 和高度 (50%) 的百分比。在该 DIV 中,我需要放置一个图像,它应该在调整浏览器大小时按比例缩放和适应。因此,图像的最大高度和最大宽度由 DIV 的高度和宽度给出。

当您更改浏览器的宽度(以及 DIV)时,图像会很好地适应,但当浏览器高度变得非常小时,图像会与下面的 DIV 重叠。

参见 JSFIDDLE 示例:https://jsfiddle.net/fnhropr3/

如何在 DIV 中垂直和水平地包含图像并保持其比例?

HTML:

<div class="section section-white">
<img src="https://www.cpp.edu/~international/study-abroad/img/jXMx4mQz6MsnhP1FSKp2TJMt.jpeg" id="image"/>
</div><!--section-->
<div class="section section-grey">
<h1>Heading</h1>
</div><!--section-->

CSS:

html{
width:100%;
height:100%;
}
body{
width:100%;
height:100%;
}
.section{
width:100%;
height:50%;
padding: 5%;
text-align:center;
}
.section-white{
background-color: #fff;
}
.section-grey{
background-color: #ccc;
}
#image{
width: 70%;
max-width: 500px;
height: auto;
max-height: 500px;
-moz-box-shadow:    0px 0px 15px #bbb;
-webkit-box-shadow:  0px 0px 15px #bbb;
box-shadow:     0px 0px 15px #bbb;
}

【问题讨论】:

  • 你可以用max-height: 100%;代替jsfiddle.net/fnhropr3/1
  • 图片可以设置为背景图片吗?
  • 使用 max-height:100% 不成比例地拉伸图像
  • 是的,我已经尝试将它与背景大小包含一起使用,但由于我需要在图像周围应用一个盒子阴影,我想直接放置 img

标签: css


【解决方案1】:

我认为使用这个效果最好。

img {
  bottom: -5000px;
  left: -5000px;
  margin: auto;
  min-height: 100%;
  min-width: 100%;
  position: absolute;
  right: -5000px;
  top: -5000px;
}

明显设置位置:relative;和溢出:隐藏;在父 div 上。无论容器大小如何,这都会定位您的图像中心。

图像还将包含其比例。

https://jsfiddle.net/fnhropr3/6/

【讨论】:

  • 太棒了!效果很好,但是我必须将您的最小高度更改为最大高度才能使其正常工作
  • 很高兴它起作用了 :) 最大高度可能会拉伸图像。最小高度将“裁剪”图像以适合。请记住这一点:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
相关资源
最近更新 更多