Proportionally reduce DIV like responsive image?

These might be silly questions ... but in CSS, a “responsive image” usually looks something like this:

img { max-width: 100%; height: auto; } 

Is it possible to use a div (or a series of nested divs) instead of an image that behaves the same as a responsive image? You will need to define a div with a width of 1000px and a height of 200px, but compress it proportionally when the container is compressed in width.

Essentially, you can do something like this:

http://codepen.io/jakobud/pen/jEKVRZ

behave like this:

http://codepen.io/jakobud/pen/MYXbZB

Is this possible anyway? If not, why? You obviously cannot add height: auto to div.two because it will override the specific DIV height.

One of the workarounds that I considered for this approach is to create a fully transparent PNG of 1000x200 size that you place in your container, which will give the desired results, but this is a complete hack. It sounds like you should be able to do this with CSS, but I'm not sure how to do it.

I am also looking for a solution that does not require jQuery.

The reason I ask for this sometimes occurs when designers ask for something like this when there is a container the size of a certain aspect ratio, but the background image is not used. In some cases, the developer wants to use a CSS gradient for the background, so I can't just use <img> , which is the aspect ratio of the container. Obviously, I cannot rely on the contents (a <h1> or something else) to dictate the shape / proportion of the container.

+6
source share
1 answer

div do not have a built-in image format, but you can use padding on a div wrapper with an absolutely positioned child to simulate aspect ratio. This is a general approach for processing videos.

 .one { position: relative; padding-bottom: 20%; /* 1000:200 */ height: 0; } .two { width: 1000px; height: 200px; background: #999; color: #FFF; text-align: center; font-family: sans-serif; max-width: 100%; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } 

Updated code: http://codepen.io/sdsanders/pen/zxaNGQ

+10
source

Source: https://habr.com/ru/post/983071/


All Articles