Can this be solved using only CSS?
I have a component that need to adapt its layout depending on the content it receives.
In this example the layout changes depending on the amount of images:
1 image (in blue)
2 images (in yellow)
3 images (in green)
16 Replies
Can be easily done
the layout you drawn
You'd need to give the rows explicit heights or give the images an explicit max-height for this to work.
If you use
fr
for grid-template-rows
, it'll fit each row height to the height of the largest imageyou can make it work using a combination of the
:has
selector (to detect the number of images) and various grid-template
configurations for each number of imageI was also thinking of using flex but I agree that grid is here better
while you can do it, and
:has
has relatively decent support, you're already using javascript or some backend language to have either one, two, or three image tags. Why not also just have a class on the image wrapper element depending on how many there are?That is a solution too
thanks for the suggestions. i've simplified it a bit by leaving out a layout when there is no image available:
so the bottom left content will shuffle into the right here.
i do think, i need javascript condition so solve this however.
so far i know i can't use
:has
to change the complete grid style depending on the amount of siblings. that is not within the capabilities of what :has
can do.you can change the
grid-template-areas
property on the parent, from something like "a"
to "a b"
to "a b" "a c"
then on img:nth-child(1)
you'd set grid-area: a
, img:nth-child(2)
you'd set grid-area: b
, img:nth-child(3)
you'd set grid-area: c
thank you for the suggestion, i'll try that tomorrow.
just pitching in here from what i've seen 😅, you could give the container a
max-height
and use the fr units for the rows whilst give the images within those divs e.g. .grid-cell > img
a height of 100%?Yup that would work, just styling preference. I typically would rather make the images or rows have a max-height than restrict the height of the entire container.
ah yeah i can see how people could prefer that 😄
i made some marginal progress, still need to make it adaptable to various data input.
almost cracked it here, not sure what else i can do, next to make isolate 2nd sibling image to resize.
https://codepen.io/symisz/pen/dywpmZQ
i think i solved it.
this almost seem to work for me:
any idea how i can remove the extra padding gap here?
https://codepen.io/symisz/pen/abPmYaj
First create a parent div with three rows, then use grid for each rows. Just take it step by step 🪜.