'How to make items scale both vertically and horizontally inside of a div with CSS?
I have a page layout that I created with a grid, inside this grid I have 4 rows, inside the second row I would like to have 4 squares that are the same class and have a 1:1 aspect ratio. I want them to scale with the page resizing so that the container that they are in always takes up the same percentage of the screen but as this container shrinks either vertically or horizontally, the items will scale to fit and be square. I have been able to get them to scale when the screen width shrinks how I would like, but if the screen height shrinks, the squares do not scale at all. Here is a codepen to the problem, and the relevant CSS and html here but I think you would better see my problem if you look at the codepen and try to shrink the page vertically.
https://codepen.io/camdenvaughan/pen/OJzEyLM
#row-container {
width: 100%;
height: 100%;
background-color: blue;
}
#row {
display: flex;
align-items: center;
justify-content: center;
flex-shrink:1;
gap: 2px;
width: 100%;
height: 100%;
background-color: aqua;
}
.square{
flex-grow: 1;
height: max-content;
aspect-ratio: 1/1;
border: 2px solid black;
background-color: red;
}
<div id="row-container">
<div id="row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
</div>
I just want to solve this, I don't really care if it uses flexbox or not, that is just what has gotten me closest to my desired outcome, so if there is a better way, please let me know.
Solution 1:[1]
One possible solution is to have flexed rectangles that contain squares:
.container {
display: flex;
align-items: stretch;
justify-content: center;
gap: 2px;
padding: 1rem;
background-color: lavender;
overflow: hidden;
resize: both;
}
.rectangle {
flex-grow: 1;
background-color: #0004; /* This just illustrates how this solution works */
}
.square {
max-height: 100%;
aspect-ratio: 1/1;
background-color: crimson;
}
Drag bottom right corner to resize
<div class="container">
<div class="rectangle">
<div class="square"></div>
</div>
<div class="rectangle">
<div class="square"></div>
</div>
<div class="rectangle">
<div class="square"></div>
</div>
<div class="rectangle">
<div class="square"></div>
</div>
<div class="rectangle">
<div class="square"></div>
</div>
<div class="rectangle">
<div class="square"></div>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zach Jensz |
