search
HomeWeb Front-endJS TutorialHow to Create Full-page Animations Using CSS

How to Create Full-page Animations Using CSS

Key Takeaways

  • Full-page animations can be created using CSS 3D and 2D Transforms and CSS Animations, providing a more performant and flexible alternative to traditional script-based animations for web content. The HTML element can be transformed using CSS Animations to achieve these effects.
  • To ensure consistent results when applying CSS Transforms to the element, regardless of the size of its contents, the size of the body element can be fixed to that of the browser window and content can be appended inside a wrapper . This approach can also mask any progressive rendering, re-layout or resource loading that can occur with complex content.
  • Animations can be set up at strategic times during the browsing experience to give the appearance of content transitioning into view when a page loads and out of view when a user clicks on a link. The optimal place to set up an animation that transitions page content into view is inline at the top of the element. The animationend event can be used to detect when an animation has completed and then trigger a navigation event.

Modern browsers like Internet Explorer 10 support CSS 3D and 2D Transforms and CSS Animations. By tapping the power of your GPU and running asynchronously from regular JavaScript, these technologies provide a more performant and flexible alternative to traditional script-based animations for Web content.

I’ve talked about how to build with CSS 3D Transforms as well as CSS Animations and Transitions in previous articles. In this article, I’d like to introduce a more “unconventional” use case for these technologies by describing the concept of “full-page animations” that can be used during the navigation process to add fluidity and continuity to browsing. Our target is to achieve a seamless browsing experience in which content smoothly appears into view when the user visits a page and transitions away when he clicks on a link or performs a relevant action.

These effects can be accomplished by transforming the HTML

element using CSS Animations. However, this use case presents some considerations that we felt were worthy of discussion, such as the effect of layout and sizing on transforming , as well as how to appropriately time page navigations so that they mesh properly with our animations.

The code samples in this post use unprefixed CSS markup as supported by IE10 Release Preview; other browsers may require vendor prefixes for the CSS Animations and CSS Transforms properties used.

Transforming a Page’s Entire Content

CSS Transforms are defined on the stylistic properties of an HTML DOM Element. For example, the markup for rotating an element 45 degrees along its Z axis would look like this:

#element {
    transform: rotateZ(45deg);
}

Attaching a transform to the

element of your HTML document works exactly the same way. So performing in order to declaratively add the same effect to your document’s you could do something like this:
body {
    transform: rotateZ(45deg);
}

Let’s look at a before-and-after shot of a page when applying a transform to the body element:

How to Create Full-page Animations Using CSS Applying a rotateZ(45deg) transform to the body element of a document.

For three dimensional transformations, the CSS Transforms specification defines the perspective property that can be specified on the parent of the element that we transforming. When transforming the

element of your content, it has to be applied to the element that resides above it in the DOM hierarchy. Doing so is straightforward:
html {
    perspective: 500px;
}

Combining this with a rotateY(45deg) transform on the

element yields the following result:

How to Create Full-page Animations Using CSS Applying a rotate(45deg) transform to with perspective: 500px set on .

We can manipulate the transform-origin property on the body element for interesting results. Let’s look at a couple of examples:

body {
    transform-origin: 50% 100%;
    transform: rotateX(45deg);
}

The above markup sets a rotation along X for the body element while shifting the origin of rotations to the bottom of the element using transform-origin. Effectively this rotates the document’s contents “into” the screen like this:

How to Create Full-page Animations Using CSS

We can also manipulate the perspective-origin property on the root element of our document to achieve an off-axis projection effect. Changing the style for to:

html {
    perspective: 500px;
    perspective-origin: 90% 50%;
}

Our page now looks like this:

How to Create Full-page Animations Using CSS

By using CSS Transforms, we can easily manipulate the visual appearance of the entirety of our page’s content. Since the usual layout and sizing rules still apply, some transforms on the body element (particularly ones that use percentage values or rely on the transform-origin property) can result in different visual effects depending on the content of our page. Recall our previous rotateX(45deg) example with transform-origin set to 50% 100%.

Below you can see the results before and after the transform is applied.

How to Create Full-page Animations Using CSS

Notice how the content does not actually pivot on the bottom of the window but rather at some point outside of the viewport. This is expected behavior for CSS Transforms: the

is laid out normally, then it is rotated along its bottom edge that is somewhere off screen. You will also notice that the actual foot print of the content has expanded (take a look at the scroll bars in the “after” picture) in order to accommodate the transformed content (the fact that we are using perspective projection makes this effect even more pronounced).

So how do we deal with arbitrarily sized content when applying transforms to our body element? Custom tailoring all content in order to ensure that the size of the body does not expand more than a certain amount may be unrealistic. Instead, we can use a simple HTML/CSS pattern that allows us to fix the size of the body element to that of the browser window and append content inside a wrapper

. The following markup achieves just that:
#element {
    transform: rotateZ(45deg);
}

The illustration below shows what happens when a page is scrolled vertically and we apply a rotateY(45deg) transform to the

element of our document directly (left) and using the wrapper pattern (right):

How to Create Full-page Animations Using CSS

The direct application of the transform results in a skewed visual result due to the off-axis projection (since we are no longer looking at the “center” of the body element). Using the wrapper pattern ensures that the element’s perspective-origin property (50% 50% by default) will always be correctly centered with relation to the

element, giving us a pleasant visual effect.

By utilizing the above pattern and setting up CSS Transforms with percentage values whenever possible, we can affect our

element in consistent ways, regardless of the size of its contents.

From Transforms to Animations

Having sorted out the intricacies of applying CSS Transforms to the

element, CSS Animations are the next step. By following the principles described above, we can create animations that bring our Web content into view (or remove it from view) in interesting ways.

Consider this basic @keyframes rule:

body {
    transform: rotateZ(45deg);
}

When applied to an element, this animation will cause it to rotate on its left side. When applied to a

element that uses our wrapper pattern the visual result is more interesting. The document will actually rotate from outside of the visible area of the browser window and into full view:

How to Create Full-page Animations Using CSS

Similarly, we can compose animations that fluidly remove our Web content from view. For example, if we wanted our page to disappear into the distance while rotating, we could use something like this:

#element {
    transform: rotateZ(45deg);
}

With the visual result being:

How to Create Full-page Animations Using CSS

Since we can use the full power of CSS Animations to affect the entirety of our Web content, we have a lot of flexibility in terms of generating these page effects (and we are certainly not limited to just using CSS Transforms). But once we have composed the effects that we want to apply to our content, how do we cause them to trigger during the page navigation process?

Attaching Animations to

Our goal is to use trigger animations at strategic times during the browser experience in order to give the appearance of content transitioning into view when a page loads and out of view when the user clicks on a link.

The first intuitive place to add an animation to the body element would be the onload JavaScript event. As it turns out however, adding an animation when onload fires is actually too late. This event actually triggers when the entirety of the content in our page has finished loading (including any images or other bandwidth-intensive resources). Attaching an animation to onload on a bandwidth-intensive page would result in our content displaying “normally,” followed by the animation triggering and re-bringing the content into view. Not exactly the effect that we were aiming for.

Alternatively, we could utilize the DOMContentLoaded event that triggers when the browser has finished parsing the DOM structure of our content (but potentially before resources have finished loading). The IE Test Drive DOMContentLoaded demo illustrates the difference between these two events. However, in cases of complex Web content, a modern browser may choose to perform “progressive” rendering, displaying the page before the entirety of the DOM tree has been loaded. In these situations, the visual result would be similar to the onload scenario.

The optimal place to set up an animation that transitions our page content in view is inline at the top of the

element. This ensures that the animation will commence right as the content is being rendered (and that the starting position of the content will be that of the from keyframe of our selected animation). A pleasant side effect of this approach is that the animation may actually mask any progressive rendering, re-layout or resource loading that can occur with complex content.

Setting up the animations that transition our content out of view is also interesting. One could assume that we could attach an onclick handler to all elements of interest in our content (for instance all tags) and just set the relevant animation properties (animation-name, animation-duration, etc.) in the callback function. However, if we do not actually delay the navigation from happening, we will not see our expected fluid transition.

This is a good opportunity to utilize the animation events described in the CSS Animations specification. In particular, we can use the animationend event to detect when the animation has completed and then trigger a navigation (by setting window.location.href, for instance). Thus our onclick will trigger the “remove-from-view” animation and register a handler for animationend on

that will ensure that the navigation event occurs.

Live Demo Available

We’ve created a demonstration and tutorial on bringing pages alive with CSS Transforms & Animations that provide depth and examples beyond what we’ve been able to show here. The tutorial itself utilizes full page animations during page navigation that work in Internet Explorer 10 on Windows 8 as well as recent versions of Chrome and Firefox.

To simply enjoy the page-to-page animations, step through the pages of the tutorial using the “Continue to …” links in the lower right corner of each page.

At the end of the tutorial we provide some additional guidance and sample code on how to incorporate these animations with your own Web content.

Wrapping it up

CSS Transforms and CSS Animations are two powerful feature-sets that enable richer and more immersive Web experiences. With a small amount of effort you can create Web pages (even static ones) that provide a fluid and almost app-like navigation experience.

If you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Practical CSS.

Frequently Asked Questions on Full-Page CSS Animations

What are the key differences between CSS animations and JavaScript animations?

CSS animations and JavaScript animations serve the same purpose of animating web elements, but they have some key differences. CSS animations are simpler and easier to implement, especially for simple animations. They are also more performance-friendly as they are handled by the browser’s rendering engine. However, CSS animations have limited control and flexibility compared to JavaScript animations. JavaScript animations, on the other hand, offer more control and flexibility, allowing for complex animations. They can be paused, reversed, or manipulated in real-time, and can also respond to user interactions.

How can I make my CSS animations responsive?

Making CSS animations responsive involves using relative units like percentages or viewport units instead of absolute units like pixels. This ensures that the animations scale properly regardless of the screen size. You can also use media queries to adjust the animations based on specific screen sizes or device types.

Can I use CSS animations with SVG?

Yes, CSS animations can be used with SVG (Scalable Vector Graphics). SVG has its own set of CSS properties that can be animated, such as fill, stroke, and transform. This allows for more complex and interesting animations compared to animating regular HTML elements.

Why are my CSS animations not working in some browsers?

Not all browsers support all CSS animation properties. For instance, Internet Explorer does not support the animation-timing-function property. To ensure cross-browser compatibility, you can use vendor prefixes like -webkit-, -moz-, -o-, and -ms- before the animation properties. You can also use tools like Autoprefixer to automatically add these prefixes.

How can I optimize the performance of my CSS animations?

To optimize the performance of CSS animations, you can limit the number of animated properties, especially those that trigger layout changes like width, height, and margin. Instead, use properties that only trigger composite changes like transform and opacity. You can also use the will-change property to inform the browser about the properties that are likely to be animated.

Can I animate the display property with CSS?

No, the display property cannot be animated with CSS. This is because it does not have intermediate states between its values. However, you can achieve a similar effect by animating the opacity and visibility properties.

How can I create a looping animation with CSS?

You can create a looping animation in CSS by using the animation-iteration-count property. By setting its value to infinite, the animation will repeat indefinitely.

Can I control the speed of my CSS animations?

Yes, you can control the speed of CSS animations using the animation-duration property. This property defines the length of time that an animation takes to complete one cycle.

How can I pause a CSS animation?

You can pause a CSS animation using the animation-play-state property. By setting its value to paused, the animation will stop running.

Can I animate the background-image property with CSS?

No, the background-image property cannot be animated with CSS. However, you can achieve a similar effect by fading between multiple background images using the opacity property.

The above is the detailed content of How to Create Full-page Animations Using CSS. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

In JavaScript, how to get parameters of a function on a prototype chain in a constructor?In JavaScript, how to get parameters of a function on a prototype chain in a constructor?Apr 04, 2025 pm 09:21 PM

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?Apr 04, 2025 pm 09:18 PM

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.