In Sass, how do we assign height based on a width's value?
Solution 1
FYI:
Using percentage value for the width
property refers to the width of the container block while the page is rendered.
While for the height
property:
The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto. A percentage height on the root element is relative to the initial containing block.
- MDN.
So even if you could achieve this with SASS, It doesn't work properly on the browser.
There are couple of solutions on SO, to keep the aspect ratio of a box:
- Responsively change div size keeping aspect ratio
- Height equal to dynamic width (CSS fluid layout)
- Maintain the aspect ratio of a div with CSS
- Keep div height relevant to aspect ratio
Solution 2
You could apply padding-bottom as a percentage. Then put an element inside the div with position absolute.
ayjay
Updated on June 04, 2022Comments
-
ayjay almost 2 years
I'm trying to assign a value for an element's height based on the width value of a browser. For example (what I'm trying to accomplish is in between the double slash)...
.myDiv { width: 35%; height: // width * 1.61 //; }
How can this be done?
-
Julian over 10 yearsSo you answer with a non-answer? No.
-
cimmanon over 10 years@Julian Technically, the answer is correct: you can't do it with the height attribute. However, it doesn't answer the question (which is a duplicate anyway).
-
Julian over 10 years@cimmanon I removed my downvote, but I think "there is no answer" should be put in comments, not as an answer. We both pointed out answers that actually solve the problem - maybe not in the way OP envisioned, but should help more than this "answer."
-
Hashem Qolami over 10 yearsIt doesn't answer the question, but it could help to point the OP in a right direction. I posted this to mention the spec, which I couldn't explain by a comment.
-
cimmanon over 10 years@HashemQolami Duplicate questions should be closed as duplicates.
-
Hashem Qolami over 10 years@cimmanon And I voted to close the question. But none of those answers have explained the issue of using percentage unit.