I have a parent div that has a child div centered inside it. What I want is that when I click on the child div it grows downwards only, not both upwards and downwards.
The two divs before I click:
The result I get when I click on div 2:
The result I'm looking for when I click on div 2:
let div2 = document.querySelector("#div2");
div2.addEventListener("click", e => {
div2.style.height = "300px";
})
#div1 {
height: 200px;
width: 200px;
outline: red solid medium;
display: flex;
justify-content: center;
align-items: center;
}
#div2 {
height: 100px;
width: 100px;
outline: blue solid medium;
}
<div id="div1">
<div id="div2"></div>
</div>
You can do it by setting position absolute
let div2 = document.querySelector("#div2");
div2.addEventListener("click", e => {
div2.style.height = "300px";
})
#div1 {
position:relative;
height: 200px;
width: 200px;
outline: red solid medium;
display: flex;
justify-content: center;
align-items: center;
}
#div2 {
position:absolute;
top:50px;
height: 100px;
width: 100px;
outline: blue solid medium;
}
<div id="div1">
<div id="div2"></div>
</div>
let div2 = document.querySelector("#div2");
// Keep the initial height of div2
const initialHeight = (div2.clientHeight);
div2.addEventListener("click", e => {
// Add top and transform property
const transformVal = initialHeight / 2;
div2.style.transform = `translateY(-${transformVal}px)`;
div2.style.top = '50%';
div2.style.height = "300px";
})
#div1 {
height: 200px;
width: 200px;
outline: red solid medium;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
#div2 {
height: 100px;
width: 100px;
outline: blue solid medium;
position: absolute;
}
<div id="div1">
<div id="div2"></div>
</div>
A bit hacky, but using an extra element this works. Definitely not responsive for various sizes though.
let div2 = document.querySelector("#div2");
div2.addEventListener("click", e => {
div2.style.height = "300px";
})
#div1 {
height: 200px;
width: 200px;
outline: red solid medium;
display: flex;
justify-content: center;
align-items: center;
}
#divc {
height: 100px;
width: 100px;
}
#div2 {
height: 100px;
width: 100px;
outline: blue solid medium;
}
<div id="div1">
<div id="divc"><div id="div2"></div></div>
</div>