1
votes

I have a DIV on a page that has a fixed width and height (600x400). However, when the viewport becomes smaller than either the DIV's width or the DIV's height, I want the DIV to resize to remain fully visible while keeping its aspect ratio the same. Additionally, I want all the elements within the DIV to resize in the same way (also maintaining the aspect ratio).

While searching for pure CSS solutions I came across the viewport units (vw, vh, vmin, vmax). I also came across max-width and max-height. The code below shows how I combined these two. However, its a solution for resizing the DIV itself, but not the contents of the 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>

Is there a pure CSS solution that allows me to:

  • Specify the width and height of the DIV without limitations (in pixels, percentages, and whatever other way)
  • Specify the width and height of the elements within the div in pixels.
  • Resize the DIV and its contents when the viewport becomes smaller than the DIV's width or height.
  • There must be decent browser support for the solution
1

1 Answers

0
votes

You could use the css3 media query see: W3Schools media query examples, also see MDN web guide on media queries. Some code examples:

@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;
    }
}

You can change any element by specifying their element/id/class/attribute name and properties you specified will change when the width of the screen is at that targeted value.