Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading