CSS fluid layout - Height equal to dynamic width

Posts: 86

CSS fluid layout - Height equal to dynamic width

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

Code: Select all

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


Code: Select all

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

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:

Code: Select all

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

<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>

- Note: "vw" units are according to the viewport (window) size.

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

Code: Select all

#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;

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

Adv. Posts: 01

Similar Topics