Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get and use css property value in css, for calc

Tags:

html

css

I wanted to get value of css property to use in the css function calc()

For Example if I want to give a total height of 100px for a component, I have to compensate the top value by subtracting it.

.element{
   top:30px;
   width: calc( 100px - get(top) );
}

is there a function like get() used above, that would let me use a css property value of the class?

I know I can declare an upper variable for top and use it around, but is there a direct means close to this?

like image 798
Abraham Avatar asked Oct 21 '25 12:10

Abraham


2 Answers

If you are open to using JavaScript, Lucas's answer is correct and can be used to get a CSS property value and then add another property using that value.

While CSS alone does allow any way of retrieving and reusing another core CSS property's value, you can create a CSS custom property and use that for both properties like this:

.element{
   --top: 30px;
   top: var(--top);
   width: calc(100px - var(--top));
}

You can name that variable whatever you like as well. it doesn't need to match the property value. This would also work:

.element{
   --my-spacing: 30px;
   top: var(--my-spacing);
   width: calc(100px - var(--my-spacing));
}
like image 106
Brandon McConnell Avatar answered Oct 24 '25 02:10

Brandon McConnell


I think that the only way to do that is using Javascript to get the value and set the width of the element through JS. I've never seen nothing that looks like what you want.

Like this below:

<script>
  const top = window.getComputedStyle(document.querySelector('.element-top')).height
  const element = document.querySelector('.element');
  element.style.height = `calc(100px + ${top})`;
</script>
like image 38
Lucas Guimaraes Avatar answered Oct 24 '25 04:10

Lucas Guimaraes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!