Home > OS >  Animation shows default div
Animation shows default div

Time:10-23

The animation works but I cannot get the sidebar to disappear off-canvas before the animation starts. The sidebar is always there. How to get the sidebar hidden in the left and only appear with the animation, that is when you click Slide? I tried display: none but then the animation does not work anymore.

input label #sidebar {
  position: fixed;
}

input:checked label #sidebar {
  height: 100%;
  width: 100%;
  animation: appear 1s;
}

@keyframes appear {
  from {
    right: 1000px;
  }
  to {
    right: 0;
  }
}
<input type="checkbox" id="slide" name="slide" />
<label for="slide">Slide</label>
<nav id="sidebar">
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
</ul>
</nav>

CodePudding user response:

Animations are good for making complex transitions to different states, but since you're simply toggling between "on" and "off", a transition would be a better candidate.

The default style of #sidebar should be hidden. You can do that by transforming it out of the screen. Then when the input is checked, transform it back into the screen.

#sidebar {
  position: fixed;
  left: 0;
  height: 100%;
  width: 100%;
  background: #d0d0d0;
  translate: -100% 0;
  transition: translate 1s ease-in-out;
}

input:checked ~ #sidebar {
  translate: 0 0;
}
<input type="checkbox" id="slide" name="slide" />
<label for="slide">Slide</label>

<nav id="sidebar">
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
  </ul>
</nav>

CodePudding user response:

#sidebar {
  transform: translateX(-1000px);
}

input:checked~#sidebar {
  height: 100%;
  width: 100%;
  animation: appear 1s forwards;
}

@keyframes appear {
  from {
    transform: translateX(-1000px);
  }
  to {
    transform: translateX(0);
  }
}
<input type="checkbox" id="slide" name="slide" />
<label for="slide">Slide</label>
<nav id="sidebar">
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
  </ul>
</nav>

Вut better use little js.

const open = document.querySelector('.open');
const close = document.querySelector('.close');
const sidebar = document.querySelector('#sidebar');

open.addEventListener('click', () => {
  sidebar.classList.add('active');
  open.disabled = true;
});
close.addEventListener('click', () => {
  sidebar.classList.remove('active');
  open.disabled = false;
});
#sidebar {
  transform: translateX(-100%);
  transition: .3s;
}

#sidebar.active {
  transform: translate(0);
}
<button >Open</button>
<nav id="sidebar">
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
  </ul>
  <button >Close</button>
</nav>

  • Related