Home > other >  height: 0; overflow: hidden; not working with padding
height: 0; overflow: hidden; not working with padding

Time:02-03

I have this piece of code, my goal is to make custom select with smooth animation. I've chosen to make my height by default 0 with overflow: hidden, and set height to auto when .active is added. But ran into problem that body is still shown. Problem seems to be with paddings

.select-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 35px 0 20px;
  background-color: #D6E7D2;
  cursor: pointer;
  transition: background 0.5s;
}

.select-body {
  height: 0;
  overflow: hidden;
  padding-top: 27px;
  padding-left: 20px;
  padding-bottom: 31px;
  background-color: #DCE9D9;
  transition: all 0.5s;
}

.select.active .select-body {
  height: auto;
}

.select-item {
  line-height: 35px;
  cursor: pointer;
  color: #499A18;
}

.select-item:not(:last-child) {
  padding-bottom: 12px;
}
<div >
  <div >
    <span >City</span>
    <div ></div>
  </div>
  <div >
    <div >Canandaigua, NY</div>
    <div >New York City</div>
    <div >Yonkers, NY</div>
    <div >Sherrill, NY</div>
  </div>
</div>

I've tried putting body in container - didn't work. And to add padding when .active is added - this causes unexpected transition behavior.

CodePudding user response:

The real problem here is that you cannot animate from height: 0; (size value) to height: auto; (keyword value), they must both be size values. You would need to know the exact expanded height. What you can do is animate the max-height from 0 to some really big size that should always be larger than the contents; in my example I use 200vh (twice the viewport height).
Also, just apply and remove the padding the same as you do with height.

const toggle = document.querySelector('.select-header')
toggle.addEventListener('click', () => toggle.parentElement.classList.toggle('active'))
.select-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 35px 0 20px;
  background-color: #D6E7D2;
  cursor: pointer;
  transition: background 0.5s;
}

.select-body {
  height: auto;
  max-height: 0;
  overflow: hidden;
  padding-top: 0;
  padding-left: 20px;
  padding-bottom: 0;
  background-color: #DCE9D9;
  transition: all 0.5s;
}

.select.active .select-body {
  max-height: 200vh;
  padding-top: 27px;
  padding-bottom: 31px;
}

.select-item {
  line-height: 35px;
  cursor: pointer;
  color: #499A18;
}

.select-item:not(:last-child) {
  padding-bottom: 12px;
}
<div >
  <div >
    <span >City</span>
    <div ></div>
  </div>
  <div >
    <div >Canandaigua, NY</div>
    <div >New York City</div>
    <div >Yonkers, NY</div>
    <div >Sherrill, NY</div>
  </div>
</div>

  • Related