I'm creating a dynamic grid using SCSS and React. My grid will always be a perfect square: 2x2 , 3x3 , 4x4 and so on.
I need the grid to be responsive and to use the maximum available space and, most of all, any grid cell must be (and remain!) a perfect square.
Inside a grid cell I may have an image (width 100% of the cell) or a text. When the text is too long, it must break and, when the amount of text exceed the available space in the square, has to use overflow: hidden without breaking the grid.
Here a very simple example:
I've tried many different ways to achieve this result: flexbox, grid, aspect-ratio, padding-bottom 100% ... but in any case the result was perfect and clear of bugs.
Now I'm using this code:
// my square grid
.my_if_answerCardGrid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
grid-auto-rows: 1fr;
grid-gap: 0.5rem;
&::before {
content: "";
width: 0;
padding-bottom: 100%;
grid-row: 1 / 1;
grid-column: 1 / 1;
}
> *:first-child {
grid-row: 1 / 1;
grid-column: 1 / 1;
}
> div {
position: relative;
display: flex;
align-items: center;
justify-content: center;
max-height: 100%;
border-radius: 10px;
padding: 0.5rem;
background-color: $my_color-3;
// tru to fix text overflow
word-break: break-word;
overflow-wrap: anywhere;
overflow: hidden;
// try to fix image overflow
> img {
max-width: 100%;
}
}
&-selected {
border: 2px solid $my_color-1;
}
}
So I have one grid container, my_if_answerCardGrid, a pseudoelement ::before to keep the square aspect with padding-bottom: 100% and I'm using flexbox inside the cells.
So far so good (it's not perfect, but acceptable).
Anyway I'm unable to keep the square aspect when there is no enough space, for example:
Any suggestion? (also tips on how to improve my css are appreciated!)