How can I pass div height from JavaScript to CSS?

606 Views Asked by At

I want to set the position to a div depending on its own height which can be different depending on the content.

This is the structure:

HTML

<div class="wrapper">
Content
</div>

CSS:

:root {
  --height: x;
}

.wrappper {
height: auto;
top: calc(100vh - var(--height));
}
2

There are 2 best solutions below

2
UmairFarooq On BEST ANSWER

.clientHeight gives you height of the object. I'm just assigning that to the CSS variable.

 let div = document.querySelector(".wrapper")
        var height = document.querySelector(':root');
        height.style.setProperty('--height', div.clientHeight + "px");
:root {
        --height: x;
    }

    .wrapper {
        outline: 1px solid red;
        height: auto;
        position: relative;
        top: calc(100vh - var(--height));
    }
<div class="wrapper">
        <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Voluptatibus, officiis! Lorem ipsum dolor sit amet
            consectetur, adipisicing elit. Dolore accusantium deserunt corrupti iure praesentium in reprehenderit
            placeat mollitia culpa labore nostrum, cumque obcaecati et sapiente dolores excepturi libero maiores
            arch</p>
    </div>

2
Steffen On

To change a CSS variable (--height) in JavaScript, you can use:

var r = document.querySelector(':root');
r.style.setProperty('--height', <YOUR_HEIGHT>+'px');

Here is a small example where we change a CSS variable (--width) on a button click:

var r = document.querySelector(':root');
r.style.setProperty('--width', '100px');

function swapSize() {
  if (getComputedStyle(r).getPropertyValue('--width') == '100px') {
    r.style.setProperty('--width', '200px');
  } else {
    r.style.setProperty('--width', '100px');
  }
}
:root {
  --width: 100px
}

div {
  height: 100px;
  width: var(--width);
  background-color: blue;
}
<div></div>
<button onclick="swapSize()">swap variable value</button>