调整DIV(具有固定的宽度和高度)及其内容的大小,同时保持其纵横比

时间:2015-08-03 19:52:16

标签: css viewport aspect-ratio

我在页面上有一个DIV,它有一个固定的宽度和高度(600x400)。但是,当视口变得小于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及其内容的大小。
  • 解决方案必须有合适的浏览器支持

1 个答案:

答案 0 :(得分:0)

您可以使用css3媒体查询查看:W3Schools媒体查询示例,另请参阅有关媒体查询的MDN网络指南。 一些代码示例:

@media only screen and (max-width: 500px) {
    body {
        background-color: yellow;
    }
}
/* Or */
@media screen and (device-aspect-ratio: 16/9), screen and (device-aspect-ratio: 16/10) {
    body {
        background-color: blue;
    }
}

您可以通过指定元素/ id /类/属性名称来更改任何元素,并且当屏幕宽度达到该目标值时,您指定的属性将会更改。