my card looks fine on the page but gets squished in the sidebar?? do i need container queries
hi all 🦉 1am here, kids are asleep, coffee #3. building a recipe site for practice and i have a recipe card, image on the left and text on the right. on small screens it stacks. i did it with a media query like teh tutorial said: .card { display: flex; flex-direction: column; gap: 1rem; } @media (min-width: 600px) { .card { flex-direction: row; } } on the main page it looks great. but i also show the same card in…
Accepted answer
Yes, this is exactly what container queries are for. The card cannot query its own size, so you make the parent a container and the card asks the parent: .card-wrap { container-type: inline-size; } .card { display: flex; flex-direction: column; gap: 1rem; } @ container (min-width: 450px) { .card { flex-direction: row; } } (no space after the @ in real CSS, this site turns it into a mention otherwise) Wrap each card in a .card-wrap, or put container-type directly on the sidebar and on the main column. Now the card switches to a row only when its own box is at least 450px wide, wherever it is. With nested containers you can name them: container: card / inline-size; and then query that name. And :has() is real, you did not dream it. .card:has(img) { ... } styles only the cards that contain an image. Works in all current browsers since the end of 2023. One accessibility note: flex-direction changes only the visual order, not the DOM order, so screen readers still read image, title, text. Good habit to check that whenever you rearrange things with CSS.