This question already has an answer here:
- Maintain the aspect ratio of a div with CSS 21 answers
Im making a responsive design, which has to keep the proportions of its elements (height to width) no matter what the screen size is, so i don't know the size in pixels for any of the elements and i can work only in %.
I can set either the width or the height as a % of the browser size, but the i have no idea how to set the other property value.
That using only CSS, making JS calculate the values is not an option.
First, I know that the OP has clearly mentioned that he is not looking for any Javascript approach, however I think it might be useful for couple of people who are still open to use Javascript as well.
Here is the answer; To set the size for both
width
andheight
in the same percentage, you can set thewidth
of the parent element towidth: 100%;
via CSS, then with Javascript you set theheight
of the parent to the size ofwidth
. Then you would have a square-shaped element as the parent.Now you can apply both
width: 10%; height: 10%;
to the child elements. Then only things you need to do in order to keep it responsive is to listen for thewindow
resize event and then you apply theheight
again only to the parent, and all children will be updated.http://jsfiddle.net/sDzHb/
Something like this will keep it responsive to the browser size:
I came across this problem last year and found an obscure solution after some tedious researching. Unfortunately it involves wrapper DIVs. The structure is simple - you have a parent DIV which contains the contents container and another DIV that sets the proportions. You set the
margin-top
of the 'proportion' DIV as percent of the width of the parent... Example:http://jsfiddle.net/twpTU/
Use CSS calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc It has pretty good adoption for modern browsers http://caniuse.com/calc as a fall back use CSS media queries and have min widths and heights to fall back on.
Obviously you could always just calculate both percentages in advance.
Div1 needs a height of 60% and the width needs to be 1/4th the height. 60% * .25 = width: 15%
http://jsfiddle.net/pU4QA/