Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive height proportional to width

Is it possible to implement the following logic usic HTML and CSS?

width: 100%; height: 30% of width; 

What I want to implement: If I decrease the width, the height will also decrease proportionally.

like image 559
fedor.belov Avatar asked Jul 18 '12 06:07

fedor.belov


People also ask

How do you make width and height responsive?

To make an image responsive, you need to give a new value to its width property. Then the height of the image will adjust itself automatically. The important thing to know is that you should always use relative units for the width property like percentage, rather than absolute ones like pixels.

What is the relationship between a graphics height and its width?

The aspect ratio of an image or video is the proportional relationship of the width to the height. You'll recognize it as two numbers separated by a colon in an x:y format. For instance, a 6×4 inch image has an aspect ratio of 3:2, whereas a 1920×1080 pixel video has an aspect ratio of 16:9.

How do you handle height in responsive design?

For the height of a div to be responsive, it must be inside a parent element with a defined height to derive it's relative height from. If you set the height of the container holding the image and text box on the right, you can subsequently set the heights of its two children to be something like 75% and 25%.


2 Answers

Padding %

This can be achieved by giving the element height:0 and padding-bottom:30%.

In all browsers, when padding is specified in %, it's calculated relative to the parent element's width. This can be a very useful feature for Responsive Design.

JSFiddle Demo

In the demo, the blue box at the top of the page is a single div. The height is responsive, and it can contain a variable amount of inline content without increasing the height. It tested fine in IE7/8/9/10, Firefox, Chrome, Safari, and Opera.

.content {     width: 100%;     height: 0;     padding-bottom: 30%; } ... <div class="content"></div> 

Padding % and absolute position

If there are any problems with using a 0-height element, the demo also has a green box that's implemented using a wrapper element and absolute position. Not sure if there are any advantages to this approach.

.wrapper {     position: relative;     width: 100%;     padding-bottom: 30%; } .wrapper .content {     position: absolute;     width: 100%;     height: 100%; } ... <div class="wrapper">     <div class="content"></div> </div> 
like image 72
Matt Coughlin Avatar answered Sep 27 '22 01:09

Matt Coughlin


This is now possible on modern browsers with vw and vh units:

width: 100vw; height: 30vw; /* 30% of width */ 

Browser support: http://caniuse.com/#feat=viewport-units

Yeah!

like image 44
ndp Avatar answered Sep 24 '22 01:09

ndp