CSS fluid layout - Height equal to dynamic width

Place to talk about website HTM elements, CSS style and design, and get help with HTML, CSS codes.
MarPlo
Posts:186

CSS fluid layout - Height equal to dynamic width

Hello,
Is it possible to set same height as width (ratio 1:1) for a html element with dynamic /fluid width, using css?
HTML:

Code: Select all

<div id="parent">
  <div id="child">width 80%, height equal to width</div>
</div>
CSS:

Code: Select all

#child {
  width: 80%;
  height: same-as-width;
}

Admin Posts:805
Simple and neet : use vw units (viewport units) for a responsive height/width according to the viewport width.
In this example, CSS does 80% of the smallest view, height or width, according to viewport.

Code: Select all

div {
  width: 80vmin;
  height: 80vmin;
}
This technique allows you to adapt the elements aspect ratio according to the height of the viewport using "vw" units.
Another example:
CSS - HTML:

Code: Select all

<style>
#parent {
  width:40vw;  /* <-- 40% of window width */
  height:80vw;  /* <-- 2 x width (1:2 aspect ratio) */
  margin:0 auto;
  background:gold;
}
#parent #child {
  width:25vw;  /* <-- 25% of window width */
  height:25vw;  /* <-- same as width (1:1 aspect ratio) */
  margin:1em auto;
  background:red;
}
</style>

<div id="parent">40% of window width. Height 1:2 aspect ratio.
  <div id="child">25% of window width. Height 1:1 aspect ratio</div>
</div>
- Note: "vw" units are according to the viewport (window) size.

Another way, using a css trick with pseudo-class.

Code: Select all

<style>
#box {
  position: relative;
  width:    50%;  /* desired width */
}

#box:before {
  content:     "";
  display:     block;
  padding-top: 100%;  /* initial ratio of 1:1 */
}

#box #content {
  position: absolute;
  top:      0;
  left:     0;
  bottom:   0;
  right:    0;
  background:blue;
}
</style>

<div id="box">
  <div id="content">content ...</div>
</div>