cssheightpaddingcalc

CSS Calc and Multiplication


I know there is probably an obvious answer for this but I'm stumped.

I've been trying to create custom calculations to determine the exact percentage based on the pixels of an element, example:

.element {
height: calc((820px / 580) * 100%);

Though it's not working, and I have no idea why? I've played around with the equation, but I think it's something about multiplication that is causing it to not print a result.

Thanks!

EDIT:

Sorry! Here is an example. Long story short, I prefer to add images as backgrounds and I was attempting to create a gallery that is a little more fancy. Rather than spending time calculating the exact percentage of the image height, I tried to make CSS do it for me. I thought the "calc()" equation was pretty straight forward but I'm doing something wrong.

The CODEPEN link below has an example of what I was trying to do, and an example of what I'm looking for.

CODEPEN LINK

HTML

<div class="content-wrap">
  <div class="calc-element">
    <div class="inner">
      <div class="aspect-prepped aspect-size">
        <div class="absolute-fill colour-green"></div>
      </div>
    </div>
  </div>
</div>

CSS

/* CSS in Question ===================== */

.calc-element .aspect-size {
  height: 0!important;
  padding-bottom: calc((820px / 580) * 100%);
}

/*======================================*/
.content-wrap {
  display: block;
  position: relative;
  max-width: 250px;
}

.calc-element {
  display: flex;
  position: relative;
  width: 100%;
  margin-top: 40px;
  justify-content: center;
  text-align: center;
  box-sizing: border-box;
}

.inner {
  display: flex;
  position: relative;
  width: 100%;
  height: 100%;
  margin-left: auto;
  margin-right: auto;
}

.aspect-prepped {
  position: relative;
  width: 100%;
  background-color: #E6E6E6;
  overflow: hidden;  
}

.absolute-fill {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.colour-green {
  background-color: #1B4925;
}

Solution

  • You cannot multiply any measurement values such as px, cm, %, etc.

    For example, you cannot do:

    calc(100px * 100px);
    

    But you can do:

    calc(100px * 100);
    

    If the result you want is in percentage you don't need to use px.

    padding-bottom: calc((820 / 580) * 100%);
    

    I believe this solves it. But the result is in percentage and not in pixels.