Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: How to scale an <img> to cover entire parent <div>? [duplicate]

Tags:

QUESTION:

http://jsfiddle.net/Log82brL/15/

The <img> isn't shrink wrapping as I would expect with min-width:100%

I'm trying to shrink the <img> until either height or width matches the container

Click anywhere in the <iframe> to toggle container shapes

Please try to edit the <img> CSS:

1) MAINTAIN ASPECT RATIO

2) COVER ENTIRE SURFACE AREA OF CONTAINER DIV

3) ONLY EDIT THE IMAGE

This centering approach looks kinda sketch but it's pretty robust

My question is specifically: scale an <img> to FILL (maintain aspect ratio but cover the entire surface) of parent <div> even as the parent <div> resizes

Maybe I could somehow use css flex box-layout or something? Maybe a transform?

ANSWER:

http://jsfiddle.net/Log82brL/17/

Set HTML source to transparent base64 pixel (credit CSS Tricks)

<img id="img" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" /> 

Use CSS background property

#img {     width: 100%;     height: 100%;     background: url(http://i.imgur.com/0BBsCUB.gif) no-repeat center;     background-size: cover; } 
like image 620
neaumusic Avatar asked Jul 02 '15 05:07

neaumusic


People also ask

How do I resize an image to a parent div?

We have to give image tag width and height as 100%. And add the object-fit property value as contain. But the difference is if parent div size is more than image size then image will be automatically resized to parent div element size.

How do I make an image fit a div in CSS?

Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.

How do you make a div full width of a parent?

Method 2: We can make the display attribute of the child container to table-row and display attribute of parent container to table, that will take all the height available from the parent div element. To cover all the width, we can make the width of parent div to 100%.


2 Answers

http://jsfiddle.net/Log82brL/7/

#img {   width: 100%;   height: 100%;   object-fit: cover; } 

object-fit: cover allows the replaced content is sized to maintain its aspect ratio while filling the element’s entire content box: its concrete object size is resolved as a cover constraint against the element’s used width and height.

like image 96
2ne Avatar answered Sep 19 '22 13:09

2ne


If you don't want to touch the container, put the background on the <img>

#img {    background: url(imgpath) no-repeat center;   background-size: cover; } 
like image 33
Light Avatar answered Sep 17 '22 13:09

Light