Как анимировать display none
Перейти к содержимому

Как анимировать display none

  • автор:

Анимация перехода display из none в block

Есть некий объект со свойством display: none . Нужно анимировать его появление, при изменении параметра display , например, на block .


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


Стандартный способ анимации через transition не работает. Но это и не удивительно:

Но даже через введение параметра opacity ничего не работает:


Будем использовать @keyframes :

Решение с обратной анимацией

Сейчас анимирован только переход из невидимого состояния в видимое. Сделаем так, чтобы работало и в обратную сторону. Как оказалось, это гораздо сложнее.

Если добавим в HTML первый класс is visible , то вначале элемент будет видимым, а потом переключаться с видимого на невидимый:


Support CSS3 Animations from objects styled with display:none.

Toggle Display CSS3 Animation

Allow keyframe CSS3 animations and reversal of animations to run on elements styled with display property.

Modern Browsers, Lightweight, Device Friendly, Skeleton Script.

Usage Case

  • The need to create lightweight bespoke animation solutions.
  • Have an html element hidden on the page using display:none; (Any method for hiding or displaying an object can be used!)
  • On an event to display:block; or display:flex; etc. the element followed by a CSS3 Animation.
  • Animation to run in reverse or run different animation and then display:none; at the end of the animation.
  • Can be used to trigger animation events in general. Showing and hiding elements is optional.


    Any version of loaded in the page <head> — v3.2.1 Tested
  • An SCSS or LESS compiler.

Quick Installation

Only required file from the project is js/jquery-toggleDisplayAnimate.js Use of the mixins FROM less or scss folder is optional but recommended. jQuery Extension

Place the jQuery Extension script before the closing <body> tag or after jQuery.

JavaScript Standalone

The standalone version can be placed in the document <head>

Creating Animations

Example below uses import/animation/mixins ; helps you to write cross browser compatible animations.

There are 3 special css class names used for the functionality:

  • .display — (Optional) The visibility styling of the object using any css method to render it but can be used for anything.
  • .animatied — The animation to use when displaying the element.
  • .revert — (Optional) The animation to use when hiding the object.

HTML Markup

Creating a key frame (LESS)

Applying Animation to element (LESS)

Creating a key frame (SCSS)

Applying Animation to element (SCSS)

Trigger an animation

toggleDisplayAnimate toggles the .display class on the element. Functionality is similar to jQuery.toggleClass.

It would be good to note at this point that since we are using class toggles only, it is possible to remedy other uses for .display and .revet other than to toggle element visibility. You are only limited by you imagination

If triggered again before the animation is complete with .revert set and using reverse direction then the animation will stop and run backwards from its current keyframe position.

If .revert is not set, the animation stops and the css styles in class .display are dropped from the element.

Tested browsers


  • Google Chrome v59 — v60
  • Microsoft Edge v40
  • Internet Explorer v11
  • Firefox v41
  • Opera v46


  • Safari v10
  • Safari Technology Preview v35

Android 6.0.1

  • Google Chrome v59 — v60

If a browser does not support CSS3 Animations then the elements will simply toggle their display state only with no animation.

There is no plan to create fallback Javascript based animations, There are other heavy weight projects this script is intended for modern browsers only.

Special Thanks

Mac Koniarek — Testing browser compatibility on Mac OSX

Toggle-Display-Animate is maintained by marcnewton. This page was generated by GitHub Pages.

Как правильно сделать анимацию с display:none?

По задумке, он плавно выплывает из-за правого края экрана. Но, сейчас, когда он за пределами экрана, он всё равно видимый. Я хочу, чтобы когда он скрылся, у него было свойство display: none
Те, изначально блок позиционирован за пределами экрана и не отображается. Потом, когда на родителе появляется соответствующий класс, элемент становится видимым и начинает плавно выезжать из-за края. Когда класс с родителя удаляется, элемент плавно уезжает за край экрана и когда полностью уедет — перестаёт отображаться.

Animating from display: none with CSS and callbacks

Animating from display: none with CSS and callbacks

Sometimes we want to make some animations for an element entrance, like a fade-in effect. It’s common to use jQuery for such cases to make simple animations, for example:

And the reason for that is because it’s simple to use that way, jQuery even provides us a callback to be called at the end of an animation.

This is very useful, but it brings us a problem, the animation in which jQuery makes use is purely Javascript.

As a good Front-end developer you should know that transitions/animations must be a CSS responsability, and by doing so, your transitions will have a better performance.

A thread on Github talks more about not using methods like these:

CSS Transitions

Well, for this kind of transition, we can make a better aproach using CSS, and we just need to add a class on the element.

However, to use CSS to make transitions brings us two problems.

Problem 1:

How can I use a callback after a transition?

You need to use a trick here, there’s an event called transitionend , in order to have a cross-browser compatibility you can do something like this:

And now you’re able to callback every animation.

Problem 2:

How to animate from a display:none element to something?

You aren’t ever animating just from one state to another, sometimes you need to animate from a hidden element.

By default you can’t animate from a display none element like the example below:

Yep, this won’t work and the explanation for this is that the element isn’t painted and occupying size on the screen, and it needs to be done before the animation.

The Reflow technique

First, we need to know what is reflow and repaint. Here is a “crash course”:

A Repaint occurs when changes are made to an element’s skin that changes visibility, but do not affect its layout. Examples of this include outline, opacity or background color.

A Reflow occurs when changes are made to an elements size, that causes a reflow and the page layout need to be calculate again to update with that change.

There’s a technique you can use to animate from display: none , what you need to do is add a class that makes the element display: block first, then add a class that will animate the element, however before adding the animation class you need to force a reflow on that element.

To force it you can just execute a method to return element’s size, because the browser needs to update the element to get the real size and then it’ll force a reflow.

This will make the element update its size, in that case, from nothing to something (from none to block), as the element is taking up space now you can animate it adding the transition class.

See the code and a working example below:

It’s not an unusual technique, it’s well safe, Bootstrap uses it too on their Modal Component.

Libraries to help

The easiest way to solve these problems and work with a cleaner code without add by your own is to use a library for css animations.

They’ll provide a good API and the difference here from jQuery’s .fadeIn for example, is that jQuery uses Javascript during the animation and these libraries will only apply css transitions through the Javascript API.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *