How to create a responsive card with an image ?
Hello, I would like to create cards to display projects I have worked on for my portfolio. I would like to create something like that.
My problem is mainly with the images, I don't really know how to display them properly on different screen sizes.
I have tried to give them a certain height in % but it messes the height of the card. I have tried to give them a fixed height in rem but it's not really responsive even with media queries.
If I set a height of 100%, the image become too big in big smartphone/tablets
Do you guys have any ideas how I can implement that ?
Here is my code :
13 Replies
Use aspect ratio instead of height or use grid
Grid cell will set the size of your element
Where should I use grid ? Because each card is already a flexbox
its okay to be flex/or grid (doesn't matter much in this scenario),
just set the image width to 100% with an aspect-ratio of 16/9 (for example). and to be sure make it object-fit: cover. (don't set a height)
but if I don't set the height, I have this result. The card is then really long. I don't know if it's because I use next.js, because when I check my dom, I see the image has a width and height, but I didn't set it
Image reset may help too
You need to take the width and height attributes off of your img tag in the html , then set aspect-ratio in your css
And object-fit: cover as mark said
I have already set object-fit : cover
wonder where the height is coming from, it should be adjusting to the flex-container with the 100% width. can't see it in the html
You gotta take off the width and height attributes from the tag
I think it's because of Next.js . Because it uses image optimization and normally you have to set width and height attirbutes
you could try
height: unset
in the cssbecause here I don't, so maybe it uses the width and height of the image by default
oh yeah
it seems to be good
I will play a bit with it and see if it's fine, thank you
np, good luck on the project!
I have another problem that I don't know if is possible to solve easily. My three cards are in a grid layout, with 1fr 1fr 1fr, but for some resolutions, the title of the first spread on two lines and so the card is bigger, but it creates a blank in the other ones. I have tried to set align-items: center in the grid, but then the two last cards are smaller than the first one