0

I am aware that similar questions have been asked before here, but I haven't seen any tackling my use case yet. I have seen this question, but I have a different issue:

  • this question is about getting the value of a CSS property, not variable. The proposed answer on the other question suggests using var(--variable) to calculate the variable and store the result into a different property (such as width). I cannot do that because my calc() expression is assigned to a property (border-radius), not a CSS variable.
  • even if I could, percentages in border radius refer to percentage of the element's width/height, while percentages in other properties, in general, refer to percentage of the element's parent width/height
  • I have no access to the element's HTML/CSS. My use case is a JavaScript library function that receives the ID of the element and has to calculate the border-radius, I cannot modify the CSS code to use variables.

I am trying to absolutely position an element on an element's border, and this should take the border radius into account. I have no control over this element (i.e. my library only gets the ID of the element). To do this, I first need to get the border radius in JavaScript. However, I don't know how to get the absolute value, in pixels, or anything that I can use:

const div = document.getElementById("div")
const style = getComputedStyle(div)

div.innerText = "Computed border-top-left-radius: " + style.borderTopLeftRadius
#div {
  position: absolute;
  width: 500px;
  height: 50px;
  
  border: solid 1px red;
  padding: 3rem;
  border-radius: calc(10% + 2rem);
}
<div id="div"></div>

As you can see, for complex CSS values, such as calc(), I can't use getComputedValue(). Writing my own calc() parser doesn't make sense, as the CSS specification might change and allow more values/calculations, also parsing in JavaScript is probably 100x slower than the native hyper-optimized browser parsing.

Is there any way to get the border-radius in pixels/any unit that I can use in JavaScript?

Chaoz
  • 2,119
  • 1
  • 20
  • 39
  • 1
    Does this answer your question? [Get computed value of CSS variable that uses an expression like calc](https://stackoverflow.com/questions/56229772/get-computed-value-of-css-variable-that-uses-an-expression-like-calc). (The unfortunate answer is: getComputedStyle won't do the math for you, you'll need to parse it in javascript.) – Daniel Beck Mar 13 '23 at 17:40

0 Answers0