Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: make div width proportional to height

Tags:

html

css

scale

This is a little tricky to explain, but: I want a responsive-height div (height: 100%) that will scale the width proportional to the height (not vice versa).

I know of this method utilising a padding-top hack to make the height proportional to the width, but I need it to work the other way around. Having said that, I'm not hugely keen on the additional requirement of absolutely-positioned elements for the content in that method, so I realise I may well be asking for the moon on a stick here.

To help visualise, here is an image:

Visual representation of desired effect

...and here is a jsFiddle, illustrating pretty much the same thing.

It is worth noting that I am already using the :before and :after pseudo-elements to vertically-align the content of the box I want to scale proportionally.

I would really, really enjoy not having to revert to jQuery, just because there's going to be an inherent requirement for resize handlers and generally more debugging all round... but if that's my only choice, then fiat.

like image 337
indextwo Avatar asked Mar 26 '14 21:03

indextwo


People also ask

How do you set height to proportional to width in CSS?

It's a good fact to note if you're doing CSS work. For proportional resizing purposes, it makes matters extremely simple: Define the width of an element as a percentage (eg: 100%) of the parent's width, then define the element's padding-top (or -bottom) as a percentage so that the height is the aspect ratio you need.

How do you make width and height responsive?

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. In the demo, the blue box at the top of the page is a single div .


1 Answers

Oh,you could probably use that "padding-top" trick.

width: 50%; height: 0; padding-bottom: 50%; 

http://absolide.tumblr.com/post/7317210512/full-css-fluid-squares

Or:

.square-box{     position: relative;     width: 50%;     overflow: hidden;     background: #4679BD; } .square-box:before{     content: "";     display: block;     padding-top: 100%; } 

http://codeitdown.com/css-square-rectangle/

The vertical padding in CSS is related to the width of the element, not the height.

like image 68
feeela Avatar answered Sep 19 '22 15:09

feeela