【发布时间】:2016-06-04 20:03:48
【问题描述】:
我希望网页上的图片放大/缩小到弹性盒的可用高度或宽度,并保持原始纵横比。
我在图片上使用了max-height:100%; max-width:100%,但这不起作用。
页面总是填满浏览器窗口而不会溢出。它有 3 行:
- 顶部固定高度的标题
- 一篇文章,图片和描述并排
- 底部固定高度的页脚
图像应该随着可用的高度或宽度放大/缩小,具体取决于图像和周围框的纵横比。
这意味着大多数情况下,图像左侧或下方存在空白空间。
这是一个示例页面:
<html><head>
<title>Title</title>
<style type="text/css">
* {font-size:100%; font:inherit; padding:0; border:0; margin:0}
body {background:#FFC; color:#333; font-family:sans-serif}
body {display:flex; flex-direction:column; height:100%}
h1 {text-align:right; margin-right:20em; background:#CAA}
article {flex:1; display:flex}
article figure {flex:1}
article figure img {display:block; max-width:100%; max-height:100%}
#description {width:20em; background:#ACA}
footer {background:#AAC}
</style>
</head><body>
<h1>Title</h1>
<article>
<figure> <img src="https://placekitten.com/987/765" /> </figure>
<div id="description">
<p>The description.</p>
</div>
</article>
<footer> Footer </footer>
</body></html>
我创建了一个JSFiddle,但它不像在单独的浏览器窗口中查看时那样将页脚固定在底部。
使用 flexbox 会很好,因为它易于布局。但是如果这不能用它来完成,我会使用绝对定位。
【问题讨论】:
-
制作一个 div 使用 flex-box 进行拉伸,将图像放入其中,提供 100% 的最大宽度和高度。我在手机上不能举个例子对不起。
-
我想我做到了,但是当窗口高度降低时图像不会缩小。
-
@Michael_B 仅关于高度。我希望图像缩放到可用的宽度或高度。
-
因为我没有找到使用 flexbox 的解决方案,所以我切换到了绝对定位。查看更新的 JSFiddle:jsfiddle.net/0nw61s4t/1