user3029697
user3029697

Reputation: 53

Fluid div with height dictated bybackground image

I have a background image in a div of 100% width. There is nothing else in the div. I want to be able to have the height of the div to always be the aspect ratio of the background image. Is there a way to do this?

So in other words when I scale down the page I want the div to scale down and maintain the same height of the background image.

I hope this makes sense,

thanks

Upvotes: 0

Views: 191

Answers (2)

Pedro Moreira
Pedro Moreira

Reputation: 965

If you use img tag, you won't need to care about vertical resizing.

<div>
   <img src="..." style="width: 100%">
</div>

Upvotes: 2

Paul Redmond
Paul Redmond

Reputation: 3296

Yes, this is possible using a combination of width, padding and background-size.

Check out this:

The key lies in padding. Padding, whether being used to define top, bottom, left, or right padding, is dependent upon the WIDTH of the containing element when defined in percents. For example, if you say “padding-top: 10%;” what you are actually saying is that the padding on the top should be 10% of the WIDTH of the containing element. So then, if you wish to make an element a responsive square, you simply write this:

width: 20%;
height: 0;
padding-bottom: 20%;
background-size: contain;

Upvotes: 4

Related Questions