1

I've got a JS variable representing a width in pixels that I'd like to use inside a CSS calc() function.

The variable is holding the width of a div's scrollbar.

let table = document.getElementById("RGtable");

let offsetWidth = RGtable.offsetWidth;
let clientWidth = RGtable.clientWidth;

function getScrollbarWidth() {
  return offsetWidth - clientWidth;
};

let scrollbarWidth = getScrollbarWidth() + "px";

let header = document.getElementById("tableHeader");

// This is where I have the problem
header.style.setProperty('width', 'calc(100% - scrollbarWidth)');

I've tried:

header.style.setProperty('width', 'calc(100% - 'getScrollbarWidth() + 'px'')');

which gives me errors, and

header.style.setProperty('width', 'calc(100% -  ${width})')

which is based off of this post.

I know I'm missing something, just can't figure out what!

1
  • 'calc(100% - 'getScrollbarWidth() is missing the + in between: 'calc(100% - ' + getScrollbarWidth() Commented Aug 4, 2022 at 7:13

1 Answer 1

1

You have to properly interpolate the string:

with backticks (not single quotes)

header.style.setProperty('width', `calc(100% - ${scrollbarWidth})`);

or with string concatenation

header.style.setProperty('width', 'calc(100% - ' + scrollbarWidth + ')');
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh right, I see where I was going wrong. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.