Jake Wilson
Jake Wilson

Reputation: 91213

Proportionally shrink a DIV similar to a responsive image?

This might be a silly questions... but in CSS, a "responsive image" is typically something like this:

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

Is it possible to use a div (or series of nested divs) instead of an image that behaves the same way that a responsive image does? You would need to define a div with width 1000px and height 200px, but have it proportionally shrink as the container shrinks in width.

Essentially, is it possible to make something like this:

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

behave like this:

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

Is this possible in any way? If not, why? You obviously can't add height: auto to the div.two because that would override the DIV's defined height.

One workaround I have considered for this approach, is to create a 1000x200 fully transparent PNG that you would place in your container, which would give the desired results, but it is a total hack. Seems like you should be able to do it with CSS but I'm not sure how.

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

The reason I'm asking for this is becomes sometimes designers have asked for something like this where there is a container that is sized with a certain aspect ratio but there is no background image used. In some cases the designer wants to use a CSS gradient for the background so I can't just use an <img> that is the aspect ratio of the container. Obviously I can't rely on the contents (a <h1> or something) to dictate the container shape/aspect ratio.

Upvotes: 7

Views: 7690

Answers (1)

Steve Sanders
Steve Sanders

Reputation: 8651

divs do not intrinsically have an aspect ratio like images, but you can use padding on a wrapper div with an absolutely positioned child to simulate the aspect ratio. This is a common approach for handling responsive 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 codepen: http://codepen.io/sdsanders/pen/zxaNGQ

Upvotes: 11

Related Questions