Codehan25 Codehan25 - 4 months ago 35
CSS Question

CSS transition not working with transform: translate

How can I realize a smooth transition for my mobile menu?

The

transform
property is working, but I want it to happen slowly..

My Sass looks like this

.mobile-nav
display: none
position: relative
width: 100%
background: $white
padding: 30px 0 20px
transform: translateY(-100%)

@media (max-width: 775px)
.mobile-nav.is-o
display: block
transform: translateY(0%)

Answer

The main obstacle you're facing is that the display property is not animatable.

Like a light switch, display: none is off and display: block is on. There's no middle ground, no fade effects, no CSS transitions.

However, there are multiple other properties you can use for transitions. Among them:

  • height
  • opacity
  • z-index
  • background-color

Here's an example:

.mobile-nav-toggle {
  font-size: 2em;
  cursor: pointer;
}
.mobile-nav {
  display: inline-block;
  overflow: hidden;
  width: 0;
  height: 0;
  opacity: 0;
  transition: width 1s, height 1s, opacity 0s 1s, background-color 0s 2s;
}
.mobile-nav-toggle:hover + .mobile-nav {
  width: 150px;
  height: 150px;
  opacity: 1;
  background-color: lightgreen;
  transition: 1s;
}
<div class="mobile-nav-toggle">&#9776;</div>
<div class="mobile-nav">
  <ul>
    <li><a>Item</a></li>
    <li><a>Item</a></li>
    <li><a>Item</a></li>
  </ul>
</div>

References:

Comments