Add animations for single-element art and element Art

Source: Internet
Author: User

Add animations for single-element art and element Art

Original article: Animating Single Div Art

Translation: nzbin

Introduction: The best way to learn tools is to try new technologies. This article introduces the use of CSS variables and several ways to add animations to a single element through "single element art. I believe you will have a deep understanding of CSS variables and CSS animations by learning the complex "single element" Examples prepared by the author.

If you dig deeper into your tools, you can use the most basic HTML to do something amazing. I'm impressed with Lynn Fisher and other people's "Single element Art" ("Single Div Art"). The so-called "Single element Art" means that you can use a Single universal<div>To create beautiful cops, the AMO museum, or pandatv.

See the Pen # dailycssimages 01: Bear Cub by Lynn Fisher (@ lynnandtonic) on CodePen.

It is hard to explain how these works are made. In fact they use background gradient, shadow, text shadow, and only one div element and::beforeAnd::afterPseudo class. Before reading this article, let's take a look at why Lynn Fisher wrote this article and how she made the single element art.

Rarely use a singledivAnimation of elements. Suppose you can changedivOr the pseudo-class elements, that's okay (like the BB-8 robot made by Lynn Fisher ). However, you cannot directly changedivPrivate ElementopacityOrtransformBecause they are not really DOM elements.

I am willing to try some different and interesting ways to learn tools. Otherwise, you may never learn tools. Because a singledivIt is not suitable for practical production work, but can be used as an exercise or challenge to exercise skills. In this spirit, we can use this technology to explore the working principle of custom attributes (CSS variables), and even providedivAnimation method. To illustrate this, we will use multiple animation methods to break down the following example:

See the Pen Single Div Accordion (Animated with CSS Variables) by Dan Wilson (@ danwilson) on CodePen.

This accordion ("accordion" refers to an instrument, not a UI component) has three main parts: the keyboard (div), Wind box (squeeze part,div::before) And buttons (div::after). Because the accordion is naturally divided into these parts, we can set each part in the CSS key frame animation.transform. The movement of the Air Box needs to be set differentlyscaleXAnd the other two parts are set to followtranslateXValue. In this way, a simple accordion is born.

See the Pen Single Div Accordion Breakdown: Transforms by Dan Wilson (@ danwilson) on CodePen.

Use CSS custom attribute Organization <div>

Adding an animation to these three parts is more direct than targeting each of them. Todiv It is very helpful to separate partial groups and name them, while Custom Attributes provide native methods. You can define-white-keyAnd--black-keyTo replace the lengthy linear gradient breakpoint to implement the piano keyboard. You can set--tea-cupAnd then set--tea-bagAnd--tea-bag-position.

The left-side style of the accordion is as follows:

background:    var(--shine),    var(--shine),    var(--button-key1, var(--button)),    var(--button-key2, var(--button)),    var(--button-key3, var(--button)),    var(--black-keys),    var(--white-keys),    var(--keyboard-base);

These variable values may have many rows (or even more than one hundred rows), but in terms of concept, variables make the keyboard-Layer Code clear and natural.

See the Pen Single Div Accordion Breakdown: Keyboard by Dan Wilson (@ danwilson) on CodePen.

Although you can also use Sass or Less, you can modify these values in the custom attributes. Now we can consider modifying--button-key2Or the decorative line of the accordion.--shineTo add an animation. There are many ways to solve this problem.

Use CSS key frames to add animations to attributes

The first method is to change the attribute value of the part you want to change in the CSS Key Frame Animation. If you want to change some parts of the background (for example, we want to change the color of the "shine" line from red to blue), you can replacebackground Attribute. Based on the preceding sample code, modify the following:

div {  /* using background definition from earlier */  --shine: linear-gradient(to right, transparent 29.5%, red 29.5%, red 70.5%, transparent 70.5%);  --shine-blue: linear-gradient(to right, transparent 29.5%, blue 29.5%, blue 70.5%, transparent 70.5%);  animation: modify-shine 2000ms infinite alternate ease-in-out;}@keyframes modify-shine {  100% {    background:      var(--shine-blue), /*these two replace the original --shine*/      var(--shine-blue),      /* the rest of the background remains unchanged */      var(--button-key1, var(--button)),      var(--button-key2, var(--button)),      var(--button-key3, var(--button)),      var(--black-keys),      var(--white-keys),      var(--keyboard-base);  }}

This gives us a lot of inspiration, especiallybackgroundAdd an animation (text-shadowAndbox-shadow The same is true ). In this example, there is a change from red to blue.

If your attributes are long enough, it will be difficult to maintain them. However, you can extract unchanged attributes to help us reduce repetitive work. We can extract the part that does not need to be added to the new variables to generate multi-level variables:

div {  --static-component:     var(--button-key1, var(--button)),    var(--button-key2, var(--button)),    var(--button-key3, var(--button)),    var(--black-keys),    var(--white-keys),    var(--keyboard-base);  background:     var(--shine),    var(--shine),    var(--static-component); }@keyframes modify-shine {  100% {    background:      var(--shine-blue),      var(--shine-blue),      var(--static-component);   }}

The three notes in the accordion aretext-shadowAdd an animation.

See the Pen Single Div Accordion Breakdown: Music Notes by Dan Wilson (@ danwilson) on CodePen.

Add animations to custom attributes in CSS Key Frames

One way to change the status is to directlykeyframes.

@keyframes {  0% {    --button1-color: var(--color-primary);  }  100% {    --button1-color: var(--color-secondary);  }}

Custom Attributes cannot be pre-defined, only usevar(…)Therefore, the attribute value is set to 50% (incorrect translation) when the value is changed ). This is the default operation for all CSS attributes without animation, so there is no transitional effect between these values.

Because of the special status I have mentioned, this is not available in most browsers. Currently, only Chrome and Opera are supported.

This is the fastest way to change the status if it is supported across browsers. If you are using Chrome and Opera for browsing, you can use this method to add an animation to the left button and right button of the accordion. For example, here is an example of "pixel art". Using this method, the eyes and eyebrows will move in a compatible browser. Only one static image is displayed in other browsers. This method has the least amount of code, but has the worst compatibility.

See the Pen Pixel Art Animated with Custom Properties by Dan Wilson (@ danwilson) on CodePen.

Add an animation to a custom property using JavaScript
var div = document.querySelector('div');var active = false;setInterval(function() {  active = !active;  div.style.setProperty('--white-key-1',     'var(--white-key-color-' + (active ? 'active' : 'default') +')')}, 1000);

The corresponding CSS is as follows:

div {  --white-key-1: var(--white-key-color-default);  --white-key-color-default: #fff;  --white-key-color-active: #ddd;  /* And a linear gradient that follows the following pattern */  background: linear-gradient(to right, var(-white-key-1) 5%, var(--white-key-2) 5%, var(--white-key-2) 10%, ...); }

See the Pen Single Div Piano Keys by Dan Wilson (@ danwilson) on CodePen.

We use JavaScript based onwhite-key-1Set its value as a variable.white-key-color-defaultOrwhite-key-color-active.

This method is very useful for switching a property (such as directly changing the size, position, or color ). This method is used in the button on the right of the accordion (if the key frame method is not supported, replace it with this method ).

See the Pen Single Div Accordion Breakdown: Right by Dan Wilson (@ danwilson) on CodePen.

The CSS of the nine buttons uses the following ring gradient by default.--color1Is light blue,--button-dimIs 1.4 vmin:

--button: radial-gradient(circle,   var(--color1) var(--button-dim),   transparent var(--button-dim));

If I want to change a button to the pressed state, I can set a specific value in CSS. For example, the fourth button is set below:

--button4: radial-gradient(circle,   var(--button4-color, var(--color1)) var(--button4-dim, var(--button-dim)),  transparent var(--button4-dim, var(--button-dim)));

The property is the same as above,--button-dimAnd--color1It is replaced by the button value in the special status and usesvar()The default value is set. The default value in the variable can be used.var(--my-specific-variable, 13px)This format is specified. We can do better, or even use the value of another variable as the default value, for example:var(--my-specific-variable, var(--my-default-variable)). The second form is the special definition of the fourth button in the instance code, which can keep the default value the same. If you want some buttons to remain unchanged by default, they can be in differentbackground-positionUse the default--buttonAttribute.

In the accordion example,--button4-colorOr--button4-dimIt is not clearly defined in CSS. So they will use--color1 And--button-dim. Finally, they use JS to modify their values and create a switch animation.

var enabled = false;setInterval(function() {  enabled = !enabled;  div.style.setProperty('--button4-dim', enabled ? '1.2vmin' : 'var(--button-dim)');  div.style.setProperty('--button4-color', enabled ? 'var(--color1alt)' : 'var(--color1)');}, 1000);

This is the same as changing the custom attribute directly in the key frame. As we have discussed,backgroundAnd*-shadowYou can set an animation for attributes (with a transitional effect,transformOropacityThe effect is not good, but it is enough for simple use ).

If we use the JS switch method andbackgroundCombined with CSStransitionAttribute, we can get a transition state instead of a skip state.

div {  transition: background 2000ms ease-in-out;}
Use requestAnimationFrame

Depending on the composition of each component, the method for changing attributes may not work. If you want to move a part, tryrequestAnimationFrame.

One of my favorite single element art is a backpack made by Tricia Katz:

See the Pen Single Div Backpack by Trish Katz (@ techxastrish) on CodePen.

I like the zip that moves back and forth. Use a custom attribute to indicate the horizontal displacement of the zipperxAnd thenrequestAnimationFrameBy changing this value, the left and right sides of the zipper can be moved.

See the Pen Single Div Backpack with CSS Variables for Animation by Dan Wilson (@ danwilson) on CodePen.

Summary

TodivThere are many ways to add animations. These methods can train your skills. To get the most extensive support, we still cannot use pure CSS, although we have made great progress. Custom Attributes can directly modify values, even if they are combined with JavaScript (we can also rely on variable naming to clarify what we are changing ).

See the Pen Single Div Animation Options by Dan Wilson (@ danwilson) on CodePen.

When you want to learn new knowledge about CSS or JavaScript, you can try to use the "single element" method. If you want to break down attributes or add animations to complex values, custom attributes will give you new ideas.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.