I am trying to create a sliding animation only using CSS. JavaScript is used just to toggle the open/close state of the element.
I can use translated
and rotateX
CSS transforms to hide/show the menu. But those techniques do not reduce/increase the height of the element, and thus the parent does not follow the children height.
I want to be able to slide up/down an element inside its parent, while the parent also collapses and expands. And I want to do this using transitions so that a sliding-up/down animation would be shown.
Here is my codesandbox
CodePudding user response:
add a class to open and close then toggle the class with js
using yourclass.classList.toggle(classname)
your updated sandbox https://codesandbox.io/s/xenodochial-benji-boil1b?file=/index.html
CodePudding user response:
I would recommend to use a transform: translate and change layout of navbar
#parent {
overflow-y: hidden;
}
#slide {
background: gray;
z-index: 30;
position: relative;
}
#slideMenu {
transform: translateY(-100%);
overflow: hidden;
z-index: -1;
transition: 1s transform ease-in;
position: relative;
}
#slideMenu.open {
transform: translateY(0);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<div id="parent">
<div id="slide">
<button>sldie</button>
</div>
<div id="slideMenu">
<div>item 1</div>
<div>item 2</div>
<div>item 3</div>
<div>item 4</div>
<div>item 5</div>
</div>
</div>
<script>
var slideMenu = document.querySelector("#slideMenu");
var slide = document.querySelector("#slide");
document.addEventListener("click", (e) => {
if (slideMenu.classList.contains("open")) {
slideMenu.classList.remove("open");
} else {
slideMenu.classList.add("open");
}
});
</script>
</body>
</html>