Search code examples
cssheightcalc

Can you use CSS calc() function to make the height of an element match its width? My attempt is not working


The calc() function is not working as I expected it to in my code.

Instead of the height being calculated to 20% of the container's width, the height is collapsing.

html:

.box {
  width: 20%;
  height: calc(20%);
  margin: auto;
  background-color: olive;
}
<div class="box">
  
</div>

I've tried adding a calculation, like "height: calc(20% - 0px);" but the height is still just collapsing to zero.

Can anyone see if I am doing something wrong? Thanks!


Solution

  • As i commented above % in height is relative to the height of the parent element and using calc() will not change the behavior as calc(20%) is the same as simply 20%.

    This function will simply do some calculation to provide a result used by your property so the logic will always be the same with or without calc().

    You need to set a height to parent container in order to your element having a height:

    .container {
      height: 100px;
    }
    
    .box {
      width: 20%;
      height: calc(20%);
      /* same result with the below
      height: calc(20% / 1);
      height: calc(20% - 0px);
      */
      margin: auto;
      background-color: olive;
    }
    
    .box-1 {
      width: 20%;
      height: 20%;
      /* same result without calc*/
      margin: auto;
      background-color: red;
    }
    
    .box-2 {
      width: 20%;
      height: calc((50% + 20px) / 2);
      /* 50% from parent height = 50px
         50px + 20px = 70px
         70px / 2 = 35px*/
      margin: auto;
      background-color: yellow;
    }
    <div class="container">
      you will see this element because height is set to container
      <div class="box">
      </div>
      <div class="box-1">
      </div>
      <div class="box-2">
      </div>
    </div>
    you will not see these elements because no height set to parent container (the body)
    <div class="box">
    </div>
    <div class="box-1">
    </div>
    <div class="box-2">
    </div>

    Now if you want to have relation between height/width of your element you may consider using variable BUT it won't work with % values:

    :root {
      --size-box:200px;
    }
    
    .box {
      width: var(--size-box);
      height: calc(0.2 * var(--size-box));
      margin: auto;
      background-color: olive;
    }
    .big {
       --size-box:400px;
    }
    .per {
       --size-box:40%;
    }
    <div class="box">
    </div>
    <div class="box big">
    </div>
    we don't see the below one because of the same issue, using % in height and no height specified in parent element
    <div class="box per">
    </div>

    And if you want to maintain aspect ratio of your element you may check this question: Maintain the aspect ratio of a div with CSS