Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

66
Views
How can I make a div grow downwards only?

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:

enter image description here

The result I get when I click on div 2:

enter image description here

The result I'm looking for when I click on div 2:

enter image description here

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>

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

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>

7 months ago · Juan Pablo Isaza Report

0

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>

7 months ago · Juan Pablo Isaza Report

0

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>

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs