0

I have a CSS class and want to use its width value to calculate its height like this:

.preview__card {
  width: 100%;
  height: calc(([width of preview__card] * x) / y);
}

Is it possible to do it this way or do I need to use JavaScript? I have looked at a lot of calc() examples but cannot seem to find anything applicable.

Thank you :)

1 Answers1

0

It is possible, with pure CSS solution - using CSS variables. Also, if your x and y variables are also dynamic, you could also change them into CSS variables.

Have a look at following article, it also shows you how you can modify CSS variables via JS, if needed. https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties#values_in_javascript

:root {
  --preview-card-width: 100%;
}

.preview__card {
  width: var(--preview-card-width);
  height: calc(var(--preview-card-width) * x) / y);
}

You could also take it further and make it a bit tidier.

:root {
  --preview-card-width: 100%;
  --preview-card-height: calc(var(--preview-card-width) * x / y);
}

.preview__card {
  width: var(--preview-card-width);
  height: var(--preview-card-height);
}
Ed T.
  • 325
  • 2
  • 12