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 >
Content
</div>
CSS:
:root {
--height: x;
}
.wrappper {
height: auto;
top: calc(100vh - var(--height));
}
CodePudding user response:
.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 >
<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>
CodePudding user response:
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>