【问题标题】:Resizing a DIV (with a fixed width and height) and its content while maintaining its aspect ratio调整 DIV(具有固定宽度和高度)及其内容的大小,同时保持其纵横比
【发布时间】: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


    【解决方案1】:

    您可以使用 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/类/属性名称来更改任何元素,并且您指定的属性将在屏幕宽度达到该目标值时更改。

    【讨论】:

      猜你喜欢
      • 2014-04-17
      • 1970-01-01
      • 2014-10-14
      • 2014-02-06
      • 2019-01-08
      • 2015-05-22
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      相关资源
      最近更新 更多