5

I have a Vue app with an element that needs to expand and collapse with a button click. The effect needs to be animated to make it less jarring. I'm using the <transition> tag for this but it doesn't work unless I hard code the element's height property in the css. This won't work because the element contains dynamic data and will have varying heights.

Here is my code:

<template>
    <input type="button" value="Toggle" v-on:click="showIt = !showIt"/>
    <transition name="test-tran">
        <div class="test-block" v-show="showIt">
            <div v-for="item in items">{{ item }}</div>
        </div>
    </transition>
</template>

<script>
    export default {
        data() {
            return {
                showIt: false
            };
        }
    }
</script>

Here is the corresponding css:

.test-block {
    /*
    adding a height makes the transition work but
    an accurate height can't be known ahead of time

    height: 100px;
    */
}

.test-tran-enter-active {
    transition: all .5s ease;
}

.test-tran-leave-active {
    transition: all .5s ease;
}

.test-tran-enter, .test-tran-leave-to
    height: 0;
}

.test-tran-leave, .test-tran-enter-to
    /*
    adding a height makes the transition work but
    an accurate height can't be known ahead of time

    height: 100px;
    */
}

Without the height property, the element shows and hides correctly but there is no animation. It just appears and disappears instantly.

How can I make the animation work without hard coding the height in the css?

d512
  • 32,267
  • 28
  • 81
  • 107

1 Answers1

1

No, it is a pure css issue. In order transition to work height must be provided. You can solve it with a hacky way though.

See How can I transition height: 0; to height: auto; using CSS?

El Danielo
  • 780
  • 1
  • 8
  • 18