Animating Bootstrap 5 dropdown

Viewed 4675

I am attempting to animate a right-aligned Bootstrap dropdown with CSS and am not able to get it working. I thought by setting the transition property to apply to the element's width property it would work, but it does not.

I can see the width of the element is initially set to 0 in my browser inspector, and is set to "auto" after the menu is made visible. I can see the transition getting applied if I adjust the width manually, but for some reason it won't happen when the menu is shown. I've tried using pixel values instead of "auto" with no change.

I'm expecting to see the menu "slide out" to the right at the same rate as the menu button rotates. Is this possible?

div.dropdown > .btn {
    transition: transform 0.8s cubic-bezier(0,-0.14,.27,1.55);
    transform: rotate(90deg);
}

div.dropdown > .btn.show {
    transform: rotate(270deg);
}

div.dropdown > .dropdown-menu {
    transition: width 0.8s cubic-bezier(0,-0.14,.27,1.55);
    width: 0;
}

div.dropdown > .btn.show + .dropdown-menu {
    width: auto;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js"></script>

<div class="dropdown dropend p-4">
    <button class="btn btn-secondary" type="button" data-bs-toggle="dropdown">
        ++
    </button>
    <ul class="dropdown-menu dropdown-menu-end">
        <li><a class="dropdown-item" href="#">Action</a></li>
        <li><a class="dropdown-item" href="#">Another action</a></li>
    </ul>
</div>

1 Answers

You can try this solution. Animation in transition is your own.

div.dropdown > .btn {
    transition: transform 0.8s cubic-bezier(0,-0.14,.27,1.55);
    transform: rotate(90deg);
}

div.dropdown > .btn.show {
    transform: rotate(270deg);
}

div.dropdown>.dropdown-menu {    
    display: inherit;
    transform: translate(69px, 19px) scaleX(0);
    transition: all 0.8s cubic-bezier(0,-0.14,.27,1.55);
    transform-origin:left;
    left: 0;
}

div.dropdown>.btn.show+.dropdown-menu {
    display: inherit;
    transform: translate(69px, 19px) scaleX(1);
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js"></script>

<div class="dropdown dropend p-4">
    <button class="btn btn-secondary" type="button" data-bs-toggle="dropdown">
        ++
    </button>
    <ul class="dropdown-menu dropdown-menu-end">
        <li><a class="dropdown-item" href="#">Action</a></li>
        <li><a class="dropdown-item" href="#">Another action</a></li>
    </ul>
</div>

Fixed for firefox

div.dropdown>.btn.show+.dropdown-menu {
    display: inherit;
    transform: translate(69px, 19px) scaleX(1);
}
Related