Css animation slide down

Pure CSS Slide-Down Animation

Sometimes something seems like it should be really easy, but it turns out to be extremely difficult. The case we’ll be checking out today is creating a slide-down animation using purely CSS. What could be so hard about that, right? Note: I’m aware this is a JavaScript site, but we’re all front-end developers here, so I’m sure this will appeal to many of you.

What Are We Talking About?

If you’re not sure what I mean by a “slide-down animation”, check out the slideDown method from jQuery. This function will take a hidden element and make it visible by increasing the element’s height from 0 to whatever the height of the element should be. That shouldn’t be too hard, right?

How You Might Try To Do It

Let’s take a look at some quick ideas of how you might expect to be able to do this easily. If you simply go by what I said earlier, you’d just set the height to 0, and then to expand it, set the height to the number that shows the whole element (with a transition as well; this is assumed for all of them, otherwise it won’t be an animation). Something like this:

Читайте также:  Мигающая кнопка на css

Note: This is using :target and links to activate the animations, so the links aren’t toggles. You’ll need to go back in the frame’s history or press “Rerun” to toggle them off.

Note that it works perfectly! Problem solved right? Yes and no. This works perfectly if you know the height of the element, but what if you don’t know the height. We’ll need a generic animation that will work no matter what height the element is. This is especially true on a responsive site, where the height can change depending on screen size.

In this case, the seemingly obvious solutions is to just set the height to auto in the expanded version’s styles.

Oh how I wish this worked. This would make everything so much easier, but sadly transitions only work on numeric values. Sure, auto does eventually compute to a numeric value, but that message doesn’t seem to get to transition , so it just pops right open instead of doing a nice animation.

So what can we do? How about CSS Transforms? We’ll set scaleY to zero and then set it to one when it should be expanded. Will that work?

When you use a transform, it doesn’t actually change the amount of space it takes up, so there are big gaps between the links instead of making that area appear at the same time the element starts expanding. So this isn’t working either. So how about we take a look at the method that I discovered.

The Answer

The answer is to set everything that can affect height (e.g. vertical padding, line-height, etc.) to 0 and then set it to the value you’d like when expanded. You need to be careful with this because there are lots of things that can affect height. For example, if there were multiple paragraphs of text inside the element, you’d need to adjust the margins between those paragraphs. If you have any images, you’ll need to make sure the height and vertical margins around it are also set to 0. This works better than just using height since you’re far more likely to know the values of each of these properties than you are to know the height of the expandable element.

Note: I also set the text color to toggle between transparent and black to give it a fading look. This is not necessary, but looks a little nicer. You can also accomplish this with opacity .

Conclusion

I’ve spend days trying to figure this out in the past. There just had to be a way! But aside from using JavaScript, which is also pretty complicated, I just couldn’t figure it out for the longest time. Now that I have it figured out, I hope it can help you as well. God bless and happy coding!

Author: Joe Zimmerman

Joe Zimmerman has been doing web development ever since he found an HTML book on his dad’s shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he’s not writing code, he’s spending time with his wife and children and leading them in God’s Word.

Источник

Pure CSS Slide-Down Animation

Join the DZone community and get the full member experience.

Sometimes something seems like it should be really easy, but it turns out to be extremely difficult. The case we’ll be checking out today is creating a slide-down animation using purely CSS. What could be so hard about that, right?

What Are We Talking About?

If you’re not sure what I mean by a «slide-down animation,» check out the slideDown method from jQuery. This function will take a hidden element and make it visible by increasing the element’s height from 0 to whatever the height of the element should be. That shouldn’t be too hard, right?

How You Might Try to Do It

Let’s take a look at some quick ideas of how you might expect to be able to do this easily. If you simply go by what I said earlier, you’d just set the height to 0, and then to expand it, set the height to the number that shows the whole element (with a transition as well; this is assumed for all of them, otherwise it won’t be an animation). Something like this:

See the Pen <a href="https://codepen.io/joezimjs/pen/NygYJy/">Pure CSS Slide Down Animation 0</a> by Joe Zim (<a href="https://codepen.io/joezimjs">@joezimjs</a>) on <a href="https://codepen.io">CodePen</a>.

Note: This is using :target and links to activate the animations, so the lnks aren’t toggles. You’ll need to go back in the frame’s history or press «Rerun» to toggle them off.

Note that it works perfectly! Problem solved right? Yes and no. This works perfectly if you know the height of the element, but what if you don’t know the height? We’ll need a generic animation that will work no matter what height the element is. This is especially true on a responsive site, where the height can change depending on screen size.

In this case, the seemingly obvious solutions is to just set the height to auto in the expanded version’s styles.

See the Pen <a href="https://codepen.io/joezimjs/pen/qxjYqN/">Pure CSS Slide Down Animation 1</a> by Joe Zim (<a href="https://codepen.io/joezimjs">@joezimjs</a>) on <a href="https://codepen.io">CodePen</a>.

Oh how I wish this worked. This would make everything so much easier, but sadly transitions only work on numeric values. Sure, auto does eventually compute to a numeric value, but that message doesn’t seem to get to transition , so it just pops right open instead of doing a nice animation.

So what can we do? How about CSS Transforms? We’ll set scaleY to zero and then set it to one when it should be expanded. Will that work?

See the Pen <a href="https://codepen.io/joezimjs/pen/zRzjzG/">Pure CSS Slide Down Animation 2</a> by Joe Zim (<a href="https://codepen.io/joezimjs">@joezimjs</a>) on <a href="https://codepen.io">CodePen</a>.

When you use a transform, it doesn’t actually change the amount of space it takes up, so there are big gaps between the links instead of making that area appear at the same time the element starts expanding. So this isn’t working either. So how about we take a look at the method that I discovered.

The Answer

See the Pen <a href="https://codepen.io/joezimjs/pen/bLRMom/">Pure CSS Slide Down Animation 3</a> by Joe Zim (<a href="https://codepen.io/joezimjs">@joezimjs</a>) on <a href="https://codepen.io">CodePen</a>.

The answer is to set everything that can affect height (e.g. vertical padding, line-height, etc.) to 0 and then set it to the value you’d like when expanded. You need to be careful with this because there are lots of things that can affect height. For example, if there were multiple paragraphs of text inside the element, you’d need to adjust the margins between those paragraphs. If you have any images, you’ll need to make sure the height and vertical margins around it are also set to 0. This works better than just using height since you’re far more likely to know the values of each of these properties than you are to know the height of the expandable element.

Note: I also set the text color to toggle between transparent and black to give it a fading look. This is not necessary, but looks a little nicer. You can also accomplish this with opacity .

Conclusion

I’ve spent days trying to figure this out in the past. There just had to be a way! But aside from using JavaScript, which is also pretty complicated, I just couldn’t figure it out for the longest time. Now that I have it figured out, I hope it can help you as well. God bless and happy coding!

Published at DZone with permission of Joseph Zimmerman , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Источник

Slide Up или Slide Down без jQuery, используя только CSS

Slide Up или Slide Down без jQuery, используя только CSS

Раньше, чтобы сделать анимацию нам бы потребовалась какая-нибудь библиотека, например jQuery, сегодня у нас есть CSS. В целом, и про него тоже можно забыть, потому что существует такое решение как Animate.css. В этой записи я покажу как сделать методы slideDown() и slideUp() из jQuery с помощью обычного CSS (не используя библиотеки и сторонние методы).

Демо

Ниже вы можете посмотреть демо, которое показывает как будет выглядить анимация, если вы будите следовать инструкциям в этой записи.

Нажмите на красный квадрат, чтобы он изменил высоту.

See the Pen NjEEKO by Alexander (@bologer) on CodePen.21516

Инструкция по создания и описание демо

У нас есть простой HTML с div элементом, у которого есть класс .slider .

Далее нам нужно добавить CSS стили, которые сделают анимацию на этом элементе.

Ниже в стилях есть три свойства, которые могут быть непонятными для многих, поэтому я их подробнее описал ниже:

  • transition-property — выбор анимаций, к которым будет относиться ниже прописанные свойства
  • transition-duration — длинная анимации
  • transition-timing-function — выбор типа анимации, в данном случае используется cubic-bezier()

.slider < overflow-y: hidden; height: 200px; width: 200px; background-color: red; cursor: pointer; transition-property: all; transition-duration: .5s; transition-timing-function: cubic-bezier(0, 1, 0.5, 1); >.slider.slider-closed

Для визуального эффекта я сделал красный куб 200 на 200 пикселей и с помощью класса-помощника — .slider-closed мы будем изменять ему высоту. Изначально у .slider стоит высота 200, .slider-closed меняет её на 50.

Смена высоты происходит с добавлением класса к .slider элементу с jQuery используя метод toggleClass().

Метод toggleClass() убирает класс, если он уже есть у элемента и добавляет если его нет.

Не хочется подключить jQuery ради двух строчек кода? Тогда воспользуйтесь JavaScript вариантом ниже:

document.getElementById(‘button’).onclick = function()

А что вы используете для создания анимации на сайте? jQuery? CSS библиотеки или что-то другое?

Источник

Оцените статью