Search code examples
jquerycssheightrootoffsetheight

How can I pass div height from JavaScript to CSS?


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));
}

Solution

  • .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>