【问题标题】:How to resize multiple images proportionally?如何按比例调整多个图像的大小?
【发布时间】:2012-09-23 12:14:51
【问题描述】:

我正在创建一个具有多个图像层的新 HTML5 页面。第一层是背景层,它是全屏图像(与屏幕大小成正比)。

第二层是另一个图像对象,我希望它处于与第一层成比例的固定位置;所以如果我改变浏览器的大小,两张图片都会改变大小,所以它们彼此成比例。

有人知道我该怎么做吗?

【问题讨论】:

  • “在与第一层成比例的固定位置”是什么意思?他们是并排的,一个在另一个里面还是......?
  • 图像是一个内另一个...意思是第一层是背景,第二层是背景上的一个对象

标签: html image-scaling


【解决方案1】:

所以,假设我们有一个“sky.jpg”背景图像和一个“sun.png”图像在它上面。

这是 HTML(5) 代码:

<div id="sky">
<img src="sun.png" id="sun">
</div>

这里是响应式 CSS:

#sky {
    width:100%; /* width in percentage, so it will adapt to user's screen */
    height:600px; /* here i've set a fixed height, but maybe it's not what you want */
    background:url(sky.jpg) top center no-repeat;
    text-align:center; /* #sun will be centered, not sure it's what you need */
    background-size:cover;
    -moz-background-size:cover;
}
#sun {
    width:15%; /* adjust it to the needed ratio */
    max-width:300px; /* max-width will prevent it from being bigger than the original image */
    min-width:20px; /* min-width is optional */
}

Live demo(调整窗口大小)


注意background-size 属性设置为cover (more info here)。

表示将保留纵横比to the smallest size such that both its width and its height can completely cover the background positioning area

这就是为什么您需要比大多数分辨率更大的图像(如果它是身体背景图像)。

此属性的其他可能值是“包含”和“自动”(have a look at the specs)。

background-size:cover;not supported by IE8(这就是为什么我们仍然添加 top center 用于后台定位)并且对于某些 FF 版本,您需要供应商前缀 (-moz-)


现在您可以为#sun 设置百分比宽度,以便它与其包含的 div 保持比例。为了防止它变得比原来的尺寸大,你可以设置一个max-width(最后是min-width)。

图像的高度会在现代浏览器中自动调整。


如果您不想在 #sky 上设置固定高度,请确保其容器的高度也不同于 auto(默认值)。

例如,如果#sky 是您的页面背景图片,您必须设置:

html, body { height:100%; }
#sky { height:100%; }

【讨论】:

    猜你喜欢
    • 2017-09-04
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2011-12-16
    相关资源
    最近更新 更多