Slide down div on click Pure CSS?

2020-06-19 03:26发布

I found this post How to create sliding DIV on click?

But all the answers are Jquery methods. Is there any way to create this with PURE CSS? I have a couple other things in mind as well...

  1. What can I add to make the slide down div stay put when scrolling
  2. Change the link that triggers the animation to "Close" in order to make the div slide back up

Here is a link to the example in that post// http://shutterbugtheme.tumblr.com/

I've also tried googling but the only results are jquery methods...

8条回答
我命由我不由天
2楼-- · 2020-06-19 03:50

This is impossible in pure CSS to recognise a click. You can do it with :hover and a transition, but that is as close as you're going to get without javascript.

.hover
{
    cursor: pointer;
    position: relative;
    z-index: 1;
}

.slide
{
    position: absolute;
    top: 0;
    z-index: -1;
    -webkit-transition: top 1s;
    -moz-transition: top 1s;
}

.hover:hover + .slide
{
    top: 50px;
}

http://jsfiddle.net/Kyle_/MaMu9/1/

Be aware though that transitions are CSS3 and will not work in IE<9 and older versions of better browsers.


Edit: after another answer was posted using the :focus property in CSS: it is possible with one caveat: you have to click outside of the element that makes it slide down to make it slide up, otherwise it works fine.

Be aware that the element must have tabindex='1' (or any number that makes sense depending on where the element is in the document) for this to work.

.hover:focus + .slide
{
    top: 50px;
    -webkit-transition: top 1s;
}

http://jsfiddle.net/Kyle_Sevenoaks/MaMu9/1/

查看更多
Bombasti
3楼-- · 2020-06-19 03:53

It can be done, although it's a little bit of a hack. The two elements that retain state (referred to in CSS as :checked) are the checkbox and radio button element. So if you associate a checkbox with a label by using a for attribute and add a div, you can get a result by reading the status of the (hidden) button:

<div class=window>
<input type=checkbox class=toggle id=punch>
<label for=punch>Punch It, Chewie<label>
<div><p>Here’s my content. Beep Boop Blurp.</p></div>
</div>

And the CSS:

input.toggle { display: none; }
input.toggle ~ div { height: 0px; margin: .2rem; overflow: hidden; }
input.toggle:checked ~ div { height: 180px; }

A further explanation and example that includes an animated open/close effect.

查看更多
登录 后发表回答