12

I want something like this:

height: calc(width + 5px);

This is just a small example but I'm ultimately looking for a way to use the set width as a part of the calculation, not a simpler way to solve the example. Any searches I do just gives examples on how to use calc() to set the width. Thanks!

Austin Griner
  • 169
  • 2
  • 6
  • 2
    Maybe look into JavaScript or some kind of CSS preprocessor. Or just use the same width value in your CSS... – Andrew Li May 08 '18 at 02:34

2 Answers2

2

Use a container query. The cqw unit represents 1% of the item's width. You can use that unit in your calc() function.

I made the item resizable in the following demo, to make the functionality easier to observe.

.container {
  container-type: inline-size;
  background: #ddd;
  
  /* Make resizable, for demo purposes */
  resize: horizontal;
  overflow: hidden;
}

.item {
  background: orange;
}

@container (min-width: 0) {
  .item {
    /* 50% of container width + 30px */
    height: calc(50cqw + 30px);
  }
}
<div class="container">
  <div class="item">Resize me!</div>
</div>

Note that, as of 2022, container queries are very new and not supported in all browsers. Modern Chrome and Safari are supported, though.

mfluehr
  • 2,832
  • 2
  • 23
  • 31
-3

The closest you might be able to come with pure CSS is combining CSS variables with calc

:root {
 --width: 100px;
}
div {
 border: 1px solid red;
 height: calc(var(--width) + 5px);
 width: var(--width);
}
<div>
test
</div>

This will let you define a CSS variable --width and use it to calculate a new height for the div.

ecg8
  • 1,362
  • 1
  • 12
  • 16