Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - How to make a div as wide as a containing child img

Tags:

css

I have this simple markup for a div:

<div class="gallery__card">
    <img class="gallery__card__img" src="1.jpg">
    <div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit</div>
</div>

But I want gallery__card to be as wide as gallery__card__img, so the text below the image doesn't take the full page width.

enter image description here

I want to avoid setting fixed widths, since this is supposed to be responsive.

Is there a way to accomplish this without JS nor fixed widths?

jsfiddle: http://jsfiddle.net/6h19oa1q/

like image 324
Boel Avatar asked Oct 14 '25 21:10

Boel


1 Answers

The reason .gallery__card is wider than gallery__card__imgis because of the text you have in .gallery__card. If you remove the text, it will stay as wide as .gallery__card__img. See here.

You can set you imgs to have width: 100% and remove your static height property like here, but then you have to make sure to maintain aspect ratios of all the images you are using; or you will have differing heights (if that's an issue).

Otherwise, you have to change the way you are constructing your elements.

like image 150
justinw Avatar answered Oct 17 '25 13:10

justinw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!