【发布时间】:2015-10-26 01:16:42
【问题描述】:
我在具有固定宽度和高度 (600x400) 的页面上有一个 DIV。但是,当视口变得小于 DIV 的宽度或 DIV 的高度时,我希望 DIV 调整大小以保持完全可见,同时保持其纵横比相同。此外,我希望 DIV 中的所有元素都以相同的方式调整大小(同时保持纵横比)。
在搜索纯 CSS 解决方案时,我遇到了视口单位(vw、vh、vmin、vmax)。我还遇到了最大宽度和最大高度。下面的代码显示了我如何将这两者结合起来。但是,它是调整 DIV 本身大小的解决方案,而不是 DIV 的内容。
<html>
<head>
<style type="text/css">
#mainDiv{
width: 800px;
height: 800px;
max-width: 90vmin;
max-height: 90vmin;
background-color: yellow;
position: relative;
}
#redSquare{
position: absolute;
top: 100px;
left: 100px;
width: 300px;
height: 300px;
background-color: red;
z-index: 5;
}
#greenSquare{
position: absolute;
top: 120px;
left: 120px;
width: 300px;
height: 300px;
background-color: green;
z-index: 10;
}
</style>
</head>
<body>
<div id="mainDiv">
<div id="greenSquare">green</div>
<div id="redSquare">red</div>
</div>
</body>
</html>
是否有一个纯 CSS 解决方案可以让我:
- 无限制地指定 DIV 的宽度和高度(以像素、百分比和任何其他方式)
- 以像素为单位指定 div 内元素的宽度和高度。
- 当视口变得小于 DIV 的宽度或高度时,调整 DIV 及其内容的大小。
- 解决方案必须有不错的浏览器支持
【问题讨论】:
标签: css viewport aspect-ratio