How to get CSS % unit to represent height instead of width

31 views Asked by At

I'm trying to make an animated dropdown/expandable component with CSS. I currently have an expanded and collapsed class, implemented as follows:

.expanded {
  margin-top: 0;
}
.collapsed {
  margin-top: -100%;
}

However, when I actually assign these classes according to the current dropdown state, it seems like -100% is equivalent to -100% of my element's width, not height like I want it to. This means the dropdown doesn't get fully collapsed when my element height is more than the width. Is there any way to change which dimension the % unit references?

If not, what would be a better way to animate the expanding/collapsing of a container?

Image of the computed sizes of my collapsed element (with margin-top: -100%): screenshot

1

There are 1 answers

0
Thomas Rio On

The way you are going about it is a little odd. I'd either use the standard max-height way. Or the best way, grid.

.dropdown {
  overflow: hidden;
  max-height: 0;
  transition: max-height 0.5s ease-out;
}

 .expanded {
    max-height: 500px; 
}

This method is straightforward but has a limitation; you need to know or estimate the maximum height your content will need.

For a more dynamic, neater solution, use grid-template-rows

.container {
    display: grid;
    grid-template-rows: 0fr auto;
    transition: grid-template-rows 0.5s ease-out;    
}

.container.expanded {
    grid-template-rows: 1fr auto;
}