Putting Things in Context With React

Context is currently an experimental API for React – but soon to be a first class citizen! There are a lot of reasons it is interesting but perhaps the most is that it allows for parent components to pass data implicitly to their children, no matter how deep the component tree is. In other words, data can be added to a parent component and then any child can tap into it.

See the Pen React Context Lights by Neal Fennimore (@nealfennimore) on CodePen.

While this is often the use case for using something like Redux, it’s nice to use if you do not need complex data management. Think about that! We create a custom downstream of data, deciding which props are passed and at which levels. Pretty cool.

Context is great in areas of where you have a lot of components that depend on a single piece of data, but are deep within the component tree. Explicitly passing each prop to each individual component can often be overwhelming and it is a lot easier just to use context here.

For example, let’s consider how we would normally pass props down the tree. In this case, we’re passing the color red using props on each component in order to move it on down the stream.

class Parent extends React.Component { render(){ return <Child color="red" />; }
} class Child extends React.Component { render(){ return <GrandChild color={this.props.color} /> }
} class GrandChild extends React.Component { render(){ return ( <div style={{color: this.props.color}}> Yep, I'm the GrandChild </div> ); }

What if we never wanted the Child component to have the prop in the first place? Context saves us having to go through the Child component with color and pass it directly from the Parent to the GrandChild:

class Parent extends React.Component { // Allow children to use context getChildContext() { return { color: 'red' }; } render(){ return <Child />; }
} Parent.childContextTypes = { color: PropTypes.string
}; class Child extends React.Component { render() { // Props is removed and context flows through to GrandChild return <GrandChild /> }
} class GrandChild extends React.Component { render() { return ( <div style={{color: this.context.color}}> Yep, I'm still the GrandChild </div> ); }
} // Expose color to the GrandChild
GrandChild.contextTypes = { color: PropTypes.string

While slightly more verbose, the upside is exposing the color anywhere down in the component tree. Well, sometimes…

There’s Some Gotchas

You can’t always have your cake and eat it too, and context in it’s current form is no exception. There are a few underlying issues that you’ll more than likely come into contact with if you end up using context for all but the simplest cases.

Context is great for being used on an initial render. Updating context on the fly? Not so much. A common issue with context is that context changes are not always reflected in a component.

Let’s dissect these gotchas in more detail.

Gotcha 1: Using Pure Components

Context is hard when using PureComponent since by default it does not perform any shallow diffing by default with context. Shallow diffing with PureComponent is testing for whether the values of the object are strictly equal. If they’re not, then (and only then) will the component update. But since context is not checked, well… nothing happens.

See the Pen React Context Lights with PureComponents by Neal Fennimore (@nealfennimore) on CodePen.

Gotcha 2: Should Component Update? Maybe.

Context also does not update if a component’s shouldComponentUpdate returns false. If you have a custom shouldComponentUpdate method, then you’ll also need to take context into consideration. To enable updates with context, we could update each individual component with a custom shouldComponentUpdate that looks something like this.

import shallowEqual from 'fbjs/lib/shallowEqual'; class ComponentThatNeedsColorContext extends React.PureComponent { // nextContext will show color as soon as we apply ComponentThatNeedsColorContext.contextTypes // NOTE: Doing the below will show a console error come react v16.1.1 shouldComponentUpdate(nextProps, nextState, nextContext){ return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState) || !shallowEqual(this.context, nextContext); }
} ComponentThatNeedsColorContext.contextTypes = { color: PropTypes.string

However, this does not solve the issue of an intermediary PureComponent between the parent and the child blocking context updates. This means that every PureComponent between the parent and child would need to have contextTypes defined on it, and they would also need to have an updated shouldComponentUpdate method. And at this point, that’s a lot of work for very little gain.

Better Approaches to the Gotchas

Fortunately, we have some ways to work around the gotchas.

Approach 1: Use a Higher Order Component

A Higher Order Component can read from context and pass the needed values on to the next component as a prop.

import React from 'react'; const withColor = (WrappedComponent) => { class ColorHOC extends React.Component { render() { const { color } = this.context; return <WrappedComponent style={{color: color}} {...this.props} /> } } ColorHOC.contextTypes = { color: React.PropTypes.string }; return ColorHOC;
}; export const Button = (props)=> <button {...props}>Button</button> // ColoredButton will render with whatever color is currently in context with a style prop
export const ColoredButton = withColor( Button );

See the Pen React Context Lights with HOC by Neal Fennimore (@nealfennimore) on CodePen.

Approach 2: Use Render Props

Render Props allow us to use props to share code between two components.

class App extends React.Component { getChildContext() { return { color: 'red' } } render() { return <Button /> }
} App.childContextTypes = { color: React.PropTypes.string
} // Hook 'Color' into 'App' context
class Color extends React.Component { render() { return this.props.render(this.context.color); }
} Color.contextTypes = { color: React.PropTypes.string
} class Button extends React.Component { render() { return ( <button type="button"> {/* Return colored text within Button */} <Color render={ color => ( <Text color={color} text="Button Text" /> ) } /> </button> ) }
} class Text extends React.Component { render(){ return (  {this.props.text}  ) }
} Text.propTypes = { text: React.PropTypes.string, color: React.PropTypes.string,

Approach 3: Dependency Injection

A third way we can work around these gotchas is to use Dependency Injection to limit the context API and allow components to subscribe as needed.

The New Context

The new way of using context, which is currently slated for the next minor release of React (16.3), has the benefits of being more readable and easier to write without the “gotchas” from previous versions. We now have a new method called createContext, which defines a new context and returns both a Provider and Consumer.

The Provider establishes a context that all sub-components can hook into. It’s hooked in via Consumer which uses a render prop. The first argument of that render prop function, is the value which we have given to the Provider. By updating the value within the Provider, all consumers will update to reflect the new value.

As a side benefit with using the new context, we no longer have to use childContextTypes, getChildContext, and contextTypes.

const ColorContext = React.createContext('color');
class ColorProvider extends React.Component { render(){ return ( <ColorContext.Provider value={'red'}> { this.props.children } </ColorContext.Provider> ) }
} class Parent extends React.Component { render(){ // Wrap 'Child' with our color provider return ( <ColorProvider> <Child /> </ColorProvider> ); }
} class Child extends React.Component { render(){ return <GrandChild /> }
} class GrandChild extends React.Component { render(){ // Consume our context and pass the color into the style attribute return ( <ColorContext.Consumer> {/* 'color' is the value from our Provider */} { color => ( <div style={{color: color}}> Yep, I'm still the GrandChild </div> ) } </ColorContext.Consumer> ); }

Separate Contexts

Since we have more granular control in how we expose context and to what components are allowed to use it, we can individually wrap components with different contexts, even if they live within the same component. We can see this in the next example, whereby using the LightProvider twice, we can give two components a separate context.

See the Pen React Context Lights with new Context by Neal Fennimore (@nealfennimore) on CodePen.


Context is a powerful API, but it’s also very easy to use incorrectly. There are also a few caveats to using it, and it can be very hard to figure out issues when components go awry. While Higher-Order Components and dependency injection offer alternatives for most cases, context can be used beneficially in isolated portions of your code base.

With the next context though, we no longer have to worry about the gotchas we had with the previous version. It removes having to define contextTypes on individual components and opens up the potential for defining new contexts in a reusable manner.

The post Putting Things in Context With React appeared first on CSS-Tricks.

Going From Dumb Little Idea to Real Website in Like 10 Minutes

I live in Bend, Oregon. I woke up with the dumbest idea ever that there should be a little food truck map website and it should be called Vend, Oregon. It’s not my finest idea, but hey, I’m full of those. Fortunately, we don’t have to spend all day on this.

1) Figure out what’s going to go on this dumb little website

Fortunately, all the hard work was already done. One of our local rags already created a list of them. They allude to a map multiple times, but it’s hard to dig it up. In searching around a bit, I found this which does have an embedded Google Map.

Perhaps this can be useful then! Let’s blow up this map and embed it properly!

2) Make the dumb site

Fortunately, Google Maps are embeddable. Let’s just slap their embed code in an HTML document:

<body> <iframe src="https://www.google.com/maps/d/embed?mid=1bg2tr60F_w395jAY-WW8JGbwSCM" width="640" height="480"></iframe>

And have it cover the entire page:

html, body { margin: 0; height: 100%; overflow: hidden;
} iframe { postion: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;

Let’s use CodePen Projects for this, as that’ll get us another step closer to having this live.

The extra files there are just a Bend logo I fired through RealFaviconGenerator.

3) Buy the dumb domain name

This is the point where you really start to question the idea. But, go ahead and pull the trigger anyway. The internet needs you.

4) It’s dumb, but it it might as well be HTTPS

One big reason to use CloudFlare is you get HTTPS even on their free plan. Might as well take advantage of that. This means pointing the nameservers from your domain registrant over to CloudFlare.

5) Deploy the CodePen Project

You can deploy the site right out of CodePen Projects.

Note that you get some IP addresses there. Add those as A Records right in CloudFlare and you’re done!

6) Bask in your dumb idea

Swear to god, 10 minutes from start to finish.

The post Going From Dumb Little Idea to Real Website in Like 10 Minutes appeared first on CSS-Tricks.

React State From the Ground Up

As you begin to learn React, you will be faced with understanding what state is. State is hugely important in React, and perhaps a big reason you’ve looked into using React in the first place. Let’s take a stab at understanding what state is and how it works.

What is State?

State, in React, is a plain JavaScript object that allows you keep track of a component’s data. The state of a component can change. A change to the state of a component depends on the functionality of the application. Changes can be based on user response, new messages from server-side, network response, or anything.

Component state is expected to be private to the component and controlled by the same component. To make changes to a component’s state, you have to make them inside the component — the initialization and updating of the component’s state.

Class Components

States is only available to components that are called class components. The main reason why you will want to use class components over their counterpart, functional components, is that class components can have state. Let’s see the difference. Functional components are JavaScript functions, like this:

const App = (props) => { return ( <div> { this.props } </div> )

If the functionality you need from your component is as simple as the one above, then a functional component is the perfect fit. A class component will look a lot more complex than that.

class App extends React.Component { constructor(props) { super(props) this.state = { username: 'johndoe' } } render() { const { username } = this.state return( <div> { username } </div> ) }

Above, I am setting the state of the component’s username to a string.

The Constructor

According to the official documentation, the constructor is the right place to initialize state. Initializing state is done by setting this.state to an object, like you can see above. Remember: state is a plain JavaScript object. The initial state of the App component has been set to a state object which contains the key username, and its value johndoe using this.state = { username: 'johndoe' }.

Initializing a component state can get as complex as what you can see here:

constructor(props) { super(props) this.state = { currentTime: 0, status: false, btnOne: false, todoList: [], name: 'John Doe' }

Accessing State

An initialized state can be accessed in the render() method, as I did above.

render() { const { username } = this.state return( <div> { username } </div> )

An alternative to the above snippet is:

render() { return( <div> { this.state.username } </div> )

The difference is that I extracted the username from state in the first example, but it can also be written as const status = this.state.username. Thanks to ES6 destructuring, I do not have to go that route. Do not get confused when you see things like this. It is important to know that I am not reassigning state when I did that. The initial setup of state was done in the constructor, and should not be done again – never update your component state directly.

A state can be accessed using this.state.property-name. Do not forget that aside from the point where you initialized your state, the next time you are to make use of this.state is when you want to access the state.

Updating State

The only permissible way to update a component’s state is by using setState(). Let’s see how this works practically.

First, I will start with creating the method that gets called to update the component’s username. This method should receive an argument, and it is expected to use that argument to update the state.

handleInputChange(username) { this.setState({username})

Once again, you can see that I am passing in an object to setState(). With that done, I will need to pass this function to the event handler that gets called when the value of an input box is changed. The event handler will give the context of the event that was triggered which makes it possible to obtain the value entered in the input box using event.target.value. This is the argument passed to handleInputChange() method. So, the render method should look like this.

render() { const { username } = this.state return ( <div> <div> <input type="text" value={this.state.username} onChange={event => this.handleInputChange(event.target.value)} /> </div> <p>Your username is, {username}</p> </div> )

Each time setState() is called, a request is sent to React to update the DOM using the newly updated state. Having this mindset makes you understand that state update can be delayed.

Your component should look like this;

class App extends React.Component { constructor(props) { super(props) this.state = { username: 'johndoe' } } handleInputChange(username) { this.setState({username}) } render() { const { username } = this.state return ( <div> <div> <input type="text" value={this.state.username} onChange={event => this.handleInputChange(event.target.value)} /> </div> <p>Your username is, {username}</p> </div> ) }

Passing State as Props

A state can be passed as props from a parent to the child component. To see this in action, let’s create a new component for creating a To Do List. This component will have an input field to enter daily tasks and the tasks will be passed as props to the child component.

Try to create the parent component on your own, using the lessons you have learned thus far.

Let’s start with creating the initial state of the component.

class App extends React.Component { constructor(props) { super(props) this.state = { todoList: [] } } render() { return() }

The component’s state has its todoList set to an empty array. In the render() method, I want to return a form for submitting tasks.

render() { const { todoList } = this.state return ( <div> <h2>Enter your to-do</h2> <form onSubmit={this.handleSubmit}> <label>Todo Item</label> <input type="text" name="todoitem" /> <button type="submit">Submit</button> </form> </div > )

Each time a new item is entered and the submit button is clicked, the method handleSubmit gets called. This method will be used to update the state of the component. The way I want to update it is by using concat to add the new value in the todoList array. Doing so will set the value for todoList inside the setState() method. Here’s how that should look:

handleSubmit = (event) => { event.preventDefault() const value = (event.target.elements.todoitem.value) this.setState(({todoList}) => ({ todoList: todoList.concat(value) }))

The event context is obtained each time the submit button is clicked. We use event.preventDefault() to stop the default action of submission which would reload the page. The value entered in the input field is assigned a variable called value, which is then passed an argument when todoList.concat() is called. React updates the state of todoList by adding the new value to the initial empty array. This new array becomes the current state of todoList. When another item is added, the cycle repeats.

A chart illustrating the cycle explained above.

The goal here is to pass the individual item to a child component as props. For this tutorial, we’ll call it the TodoItem component. Add the code snippet below inside the parent div which you have in render() method.

<div> <h2>Your todo lists include:</h2> { todoList.map(i => <TodoItem item={i} /> )}

You’re using map to loop through the todoList array, which means the individual item is then passed to the TodoItem component as props. To make use of this, you need to have a TodoItem component that receives props and renders it on the DOM. I will show you how to do this using functional and class components.

Written as a functional component:

const TodoItem = (props) => { return ( <div> {props.item} </div> )

For the class component, it would be:

class TodoItem extends React.Component { constructor(props) { super(props) } render() { const {item} = this.props return ( <div> {item} </div> ) }

If there is no need to manage state in this component, you are better off using functional component.

Leveling Up

You will be handling state very often while developing React application. With all the areas covered above, you should have the confidence of being able to dive into the advanced part of state management in React. To dig deeper, I recommend React’s official documentation on State and Lifecycle as well as Uber’s React Guide on Props vs State.

The post React State From the Ground Up appeared first on CSS-Tricks.

Theming With Variables: Globals and Locals

Cliff Pyles contributed to this post.

Setting CSS variables to theme a design system can be tricky: if they are too scoped, the system will lose consistency. If they are too global, you lose granularity.

Maybe we can fix both issues. I’d like to try to boil design system variables down to two types: Global and Component variables. Global variables will give us consistency across components. Component variables will give us granularity and isolation. Let me show you how to do it by taking a fairly simple component as an example.

Heads up, I’ll be using CSS variables for this article but the concept applies to preprocessor variables as well.

Global-scoped variables

System-wide variables are general concepts defined to keep consistency across your components.

Starting with an .alert component as an example, let’s say we want to keep consistency for all of our spaces on margins and paddings. We can first define global spacers:

:root { --spacer-sm: .5rem; --spacer-md: 1rem; --spacer-lg: 2rem;

And then use on our components:

/* Defines the btn component */
.btn { padding: var(--spacer-sm) var(--spacer-md);
} /* Defines the alert component */
.alert { padding: var(--spacer-sm) var(--spacer-md);

The main benefits of this approach are:

  • It generates a single source of truth for spacers, and a single point for the author using our system to customize it.
  • It achieves consistency since every component follows the same spacing.
  • It produces a common point of reference for designers and developers to work from. As long as the designers follow the same spacing restrictions, the translation to code is seamless.

But it also presents a few problems:

  • The system loses modularity by generating a dependency tree. Since components depend on global variables, they are no longer isolated.
  • It doesn’t allow authors to customize a single component without overwriting the CSS. For example, to change the padding of the alert without generating a system wide shift, they’d have to overwrite the alert component:
.alert { padding-left: 1rem; padding-right: 1rem;

Chris Coyier explains the idea of theming with global variables using custom elements in this article.

Component-scoped variables

As Robin Rendle explain in his article, component variables are scoped to each module. If we generate the alert with these variables, we’d get:

.alert { --alert-color: #222; color: var(--alert-color); border-color: var(--alert-color);

The main advantages are:

  • It creates a modular system with isolated components.
  • Authors get granular control over components without overwriting them. They’d just redefine the value of the variable.

There is no way to keep consistency across components or to make a system wide change following this method.

Let’s see how we can get the best of both worlds!

The two-tier theming system

The solution is a two-layer theming system where global variables always inform component variables. Each one of those layers follow a set of very specific rules.

First tier: Global variables

The main reason to have global variables is to maintain consistency, and they adhere to these rules:

  • They are prefixed with the word global and follow the formula --global--concept--modifier--state--PropertyCamelCase
    • a concept is something like a spacer or main-title
    • a state is something like hover, or expanded
    • a modifier is something like sm, or lg
    • and a PropertyCamelCase is something like BackgroundColor or FontSize
  • They are concepts, never tied to an element or component
    • this is wrong: --global-h1-font-size
    • this is right: --global--main-title--FontSize

For example, a global variable setup would look like:

:root { /* --global--concept--size */ --global--spacer--sm: .5rem; --global--spacer--md: 1rem; --global--spacer--lg: 2rem; /* --global--concept--PropertyCamelCase */ --global--main-title--FontSize: 2rem; --global--secondary-title--FontSize: 1.8rem; --global--body--FontSize: 1rem; /* --global--state--PropertyCamelCase */ --global--hover--BackgroundColor: #ccc;

Second tier: Component variables

The second layer is scoped to theme-able component properties and follow these rules:

  • Assuming we are writing BEM, they follow this formula: --block__element--modifier--state--PropertyCamelCase
    • The block__element--modifier the selector name is something like alert__actions or alert--primary
    • a state is something like hover or active
    • and if you are not writing BEM class names the same principles apply, just replace the block__element--modifier with your classname
  • The value of component scoped variables is always defined by a global variable
  • A component variable always has a default value as a fallback in case the component doesn’t have the dependency on the global variables

For example:

.alert { /* Component scoped variables are always defined by global variables */ --alert--Padding: var(--global--spacer--md); --alert--primary--BackgroundColor: var(--global--primary-color); --alert__title--FontSize: var(--global--secondary-title--FontSize); /* --block--PropertyCamelCase */ padding: var(--alert--Padding, 1rem); /* Sets the fallback to 1rem. */
} /* --block--state--PropertyCamelCase */
.alert--primary { background-color: var(--alert--primary--BackgroundColor, #ccc);
} /* --block__element--PropertyCamelCase */
.alert__title { font-size: var(--alert__title--FontSize, 1.8rem);

You’ll notice that we are defining locally-scoped variables with global variables. This is key for the system to work since it allows authors to theme the system as a whole. For example, if they want to change the primary color across all components they just need to redefine --global--primary-color.

On the other hand each component variable has a default value so a component can stand on its own, it doesn’t depend on anything and authors can use it in isolation.

This setup allows for consistency across components, it generates a common language between designers and developers since we can set the same global variables in Sketch as bumpers for designers, and it gives granular control to authors.

Why does this system work?

In an ideal world, we as creators of a design system, expect “authors” or users of our system to implement it without modifications, but of course, the world is not ideal and that never happens.

If we allow authors to easily theme the system without having to overwrite CSS, we’ll not only make their lives easier but also reduce the risk of breaking modules. At the end of the day, a maintainable system is a good system.

The two-tier theming system generates modular and isolated components where authors have the possibility to customize them at a global and at a component level. For example:

:root { /* Changes the secondary title size across the system */ --global--secondary-title--FontSize: 2rem;
} .alert { /* Changes the padding on the alert only */ --alert--Padding: 3rem;

What values should became variables?

CSS variables open windows to the code. The more we allow authors in, the more vulnerable the system is to implementation issues.

To keep consistency, set global variables for everything except layout values; you wouldn’t want authors to break the layout. And as a general rule, I’d recommend allowing access to components for everything you are willing to give support.

For the next version of PatternFly, an open source design system I work on, we’ll allow customization for almost everything that’s not layout related: colors, spacer, typography treatment, shadows, etc.

Putting everything together

To show this concept in action I’ve created a CodePen project:

Global variables are nestled in _global-variables.scss. They are the base to keep consistency across the system and will allow the author to make global changes.

There are two components: alert and button. They are isolated and modular entities with scoped variables that allow authors to fine tune components.

Remember that authors will use our system as a dependency in their project. By letting them modify the look and feel of the system through CSS variables, we are creating a solid code base that’s easier to maintain for the creators of the system and better to implement, modify, and upgrade to authors using the system.

For example, if an author wants to:

  • change the primary color to pink across the system;
  • change the danger color to orange just on the buttons;
  • and change the padding left to 2.3rem only on the alert…

…then this is how it’s done:

:root { // Changes the primary color on both the alert and the button --global--primary--Color: hotpink;
} .button { // Changes the danger color on the button only without affecting the alert --button--danger--BackgroundColor: orange; --button--danger--hover--BorderColor: darkgoldenrod;
} .alert { // Changes the padding left on the alert only without affecting the button --alert--PaddingLeft: 2.3rem;

The design system code base is intact and it’s just a better dependency to have.

I am aware that this is just one way to do it and I am sure there are other ways to successfully set up variables on a system. Please let me know what you think on the comments or send me a tweet. I’d love to hear about what you are doing and learn from it.

The post Theming With Variables: Globals and Locals appeared first on CSS-Tricks.

Animate a Container on Mouse Over Using Perspective and Transform

I’ve been working on a website in which large pictures are displayed to the user. Instead of creating a typical lightbox effect (a zoom-in animation with a black overlay) for these large pictures, I decided to try and make something more interactive and fun. I ended up coding an image container that tilts as the user moves the mouse cursor above it.

Here’s the final version:

See the Pen MrLopq by Mihai (@MihaiIonescu) on CodePen.

This effect is achieved through CSS and JavaScript. I figured I’d make a little tutorial explaining how each part works so you could easily reproduce it or extend it.

I recommend reading up on the almanac entries for perspective and transform before we get started. We’re going to refer to these properties through the post and it’s a good idea to be familiar with them.

Let’s get down to it.


First, we need a container with another inner element. The container will help with the perspective.

<div id="container"> <div id="inner"></div>

For demonstration purposes, let’s center the card exactly in the middle of the screen:

body { /* Full screen width and height */ width: 100%; min-height: 100vh; /* Centers the container in the middle of the screen */ display: flex; justify-content: center; align-items: center; margin: 0; background-color: rgb(220, 220, 220);
} #container { /* This will come into play later */ perspective: 40px;
} #inner { width: 20em; height: 18em; background-color: white;

This gives us a white card that is positioned directly in the center of a light gray background. Note that we’ve set the perspective of the #container to 40px which does nothing at this point because we have not created any transforms. That will be handled later in the JavaScript.

See the Pen 3D Image Container – Part 0 by Mihai (@MihaiIonescu) on CodePen.

Let’s Start Scripting

Here’s the outline for what we’re doing:

var container = document.getElementById('container');
var inner = document.getElementById('inner'); var onMouseEnterHandler = function(event) { update(event);
var onMouseLeaveHandler = function() { inner.style = "";
var onMouseMoveHandler = function(event) { if (isTimeToUpdate()) { update(event); }
}; container.onmouseenter = onMouseEnterHandler;
container.onmouseleave = onMouseLeaveHandler;
container.onmousemove = onMouseMoveHandler;

And here is what all those things are (or will) be doing:

  • Handler Functions: these functions handle the events as they happen. We want to decide what happens when the cursor enters, moves over, and leaves the container, so each of those has a handler.
  • Update Function: We haven’t coded this yet but its goal will be to update the 3D rotation of our #inner div.
  • Time to Update Function: This is another function we haven’t coded yet but it will return true when an update is required. This is a way to reduce the number of calls to the update() function and improve the performance of our script.
  • Event: This is a JavaScript object that describes the event that occurred.

The code above will:

  • Update the 3D rotation of the inner div as soon as the mouse enters the container.
  • Update the 3D rotation of the inner div when the appropriate time comes as the mouse moves over the container.
  • Reset the style of the inner div when the mouse leaves the container.

Is it Time to Update?

Let’s add the function that decides when to update the 3D rotation of the #inner div.

var counter = 0;
var updateRate = 10;
var isTimeToUpdate = function() { return counter++ % updateRate === 0;

When the counter reaches the updateRate, an update will be made.

At this point, you can try replacing the update function by a console.log() and play with the updateRate to see how it all works together.

The Mouse

Next up is the mouse object. This one is a little more complex than the other sections. Still, it’s not that difficult to understand, but the code can seem intimidating, especially if you’re new to JavaScript.

// Init
var container = document.getElementById('container');
var inner = document.getElementById('inner');
// Mouse var mouse = { _x: 0, _y: 0, x: 0, y: 0, updatePosition: function(event) { var e = event || window.event; this.x = e.clientX - this._x; this.y = (e.clientY - this._y) * -1; }, setOrigin: function(e) { this._x = e.offsetLeft + Math.floor(e.offsetWidth/2); this._y = e.offsetTop + Math.floor(e.offsetHeight/2); }, show: function() { return '(' + this.x + ', ' + this.y + ')'; }
// Track the mouse position relative to the center of the container.

Again, let’s walk through this together.

  • show(): Displays the current position of the mouse (if you want to do some debugging in the browser’s console).
  • setOrigin(e): Sets the coordinates (0,0) of our mouse object at the center of the element (e).
  • updatePosition(): Updates the current position of our mouse object, relative to (0,0).

The last line of code mouse.setOrigin(container) snaps the coordinates (0,0) of our mouse object to the center of our container. Here’s an example that illustrates it.

See the Pen 3D Image Container – Part 1 by Mihai (@MihaiIonescu) on CodePen.

The idea behind all this is to add more rotation to our #inner div as you move the mouse farther from the center of the container.

Update Styles on Mouse Position

Here’s our update function:

var update = function(event) { mouse.updatePosition(event); updateTransformStyle( (mouse.y / inner.offsetHeight/2).toFixed(2), (mouse.x / inner.offsetWidth/2).toFixed(2) );
}; var updateTransformStyle = function(x, y) { var style = "rotateX(" + x + "deg) rotateY(" + y + "deg)"; inner.style.transform = style; inner.style.webkitTransform = style; inner.style.mozTransform = style; inner.style.msTransform = style; inner.style.oTransform = style;
  • update(): Updates the mouse position and updates the style of the #inner div.
  • updateTransformStyle(): Updates the style for each vendor prefix.

Are We Done?

We’d better do some testing! Looks like we get a change in perspective when the mouse cursor enters and exits the card, but it’s not as smooth as it could be:

See the Pen 3D Image Container – Part 2 by Mihai (@MihaiIonescu) on CodePen.

Oh right! We told it to update the rotation of our #inner div every time the counter hits the updateRate. This produces a clunky transition between updates.

How do we solve that? CSS transitions.

Adding Transitions

#inner { transition: transform 0.5s;

These are arbitrary numbers. You can play with the perspective and transform values to make the effect more or less dramatic as you see fit.

See the Pen 3D Image Container – Part 3 by Mihai (@MihaiIonescu) on CodePen.

Note that resizing the page will cause some problems because the position of the container changes in the page. The solution is to re-center your mouse object in your container after the page is resized.

Wrapping Up

We’re done! Now we have a container for making an element a little more interactive. The demo at the beginning of this post uses an image inside of the container, but this can be used for other things besides images, including forms, modals, or just about any other content you drop in the container. Go experiment!

The post Animate a Container on Mouse Over Using Perspective and Transform appeared first on CSS-Tricks.

CSS-Tricks Chronicle XXXIII

It’s been many months since our last CSS-Tricks Chronicle. As a reminder, these are just little roundups of news of a slightly more personal nature and that of the site itself and surrounding projects.

Last update, I wasn’t even a dad yet! That’s changed 😍. My daughter is going in for her four-month checkup today!

I’m also working out of a brand new office here in Bend, Oregon. We split the space with CraftCMS. It’s the first time I’ve had an office that I have real (part) ownership over. We’ve built out a kitchen area in it and are decorating it and fleshing it out to be useful and fun for all of us.

One particularly cool thing, we splurged on a VocalBooth. It’s got the whole medium-fancy podcasting setup in there, so it’s pretty darn good sound quality for the podcasting we do. Plus it’s a nice place to take a call or meeting as well.

I made a round of updates to my microsite The Power of Serverless for Front-End Developers. My goal with that site is to explain the idea to the best of my ability and how it can be a useful thing to know about particular for front-end developers to do more with the skills they already have. Once you’re sold on that, it’s still a huge world to wrap your head around. One of the issues is understanding how many different services are out there and what roles they are trying to play. So the Services section is decently fleshed out and organized to help with that.

Over on CodePen Radio, I got to chat about all this with Marie Mosley. That’s the first time I’ve really talked about it, so it kinda resulted in a big ol’ thought dump.

I’ve had so many thoughts about this “serverless” stuff, I figured I’d formulate them into a proper conference talk. I’m not doing too many of those this year, but I’ll definitely be at An Event Apart Seattle (April 2-4), and Front-End Design Conference (April 25-27). Come!

I got to speak with Jonathan Denwood and John Locke on the WP-Tonic Podcast.

Tons going on at CodePen, of course. We’re always podcasting all about that, so if you’re particularly interested in behind-the-scenes CodePen, CodePen Radio is your friend. As I imagine any business, we’re always hard at work on a mix of projects. Some largely internal, like rearchitechting our email system, and some directly for our users, like rewriting our realtime systems to make features like Collab Mode way better.

As the year flipped over, of course we rounded up the Most Hearted list, so if you missed that, check it out.

ShopTalk just had a major milestone! Our 300th episode! Dave and I take the opportunity to talk about then and now. We’ve had loads of fun and educational episodes this year though, so if you just pick and choose episodes to listen to, I bet you’ll find one worth a crack.

The post CSS-Tricks Chronicle XXXIII appeared first on CSS-Tricks.

Some Things About `alt` Text

I’m sure you know about alt text. It’s the attribute on the image tag that has the important task of describing what that image is for someone who can’t see it for any reason. Please use them.

I don’t want to dimish the please use them message, but some interesting alt-text-related things have come up in my day-to-day lately that are related.

When you don’t

Hidde de Vries wrote You don’t always need alternative text recently:

But when an icon has a word next to it, for example ‘Log out’, the icon itself is decorative and does not need an alternative text:

<button type="button"><img src="close.svg" alt="" /> Close</button>

In this case we can leave the alt attribute empty, as otherwise a screenreader would announce ‘button – close close’.

I would think in a perfect world because that icon is entirely decorative that applying it via CSS would be ideal, but the point stands: if you have to use an image, alt text hurts more than it helps here.

Can we get it for free?

Computers are pretttttty smart these days. Perhaps they could look at our images and offer up descriptions without us manually having to type them.

Sarah’s demo uses a Computer Vision API to do that.

What about figcaption?

I hate to say it, but I’m not particularly good at writing alt text descriptions for images in blog posts right here on CSS-Tricks. It’s a problem we need to fix with process changes. We do often use <figcaption> though to add text that’s related to an image. The way that text is often crafted feels like alt text to me. It describes what’s going on in the image.

I was asking around about this, and Zell Liew told me he does the same thing:

I actually have the same question. Most of my figcaptions are used to describe the image so readers understand what the image is about.

In my mind, I figured it would be worse to drop the exact copy from the figcaption into the alt text, as someone who was reading alt text would then essentially read the same description twice.

I also talked to Eric Bailey who had an interesting idea.

<figure> <img src="screenshot.png" alt="Screenshot of Chrome displaying a split view. On the left is a page full of image thumbnails comparing pre and post-optimization filesize. On the right is Chrome developer tools showing paint rasterize duration for the images. With a 6x CPU slowdown, the longest Paint Raster took 0.27ms, AKA 0.00027 seconds."> <figcaption aria-hidden="true"> With a 6x CPU slowdown, the longest Paint Raster took 0.27ms, AKA 0.00027 seconds. </figcaption>


  • Preserves figure styling
  • Avoids nulling alt, which can be problematic for some screen readers
  • Keeps the description close to the content and communicates point to SR users
  • Communicates significant takeaway to visual readers without duplicating reading for SR users
  • Uses an aria property designed to be used outside of forms

I’d stress that he considered this just an idea and it hasn’t been heavily vetted by the larger accessibility community. If there are any of you out there reading, what do you think?

Eric’s demo used a more verbose alt text than the figcaption, but it seems like the pattern would be fine even if they were identical.

Little reminder: Twitter has alt text

But you need to enable the feature.

The post Some Things About `alt` Text appeared first on CSS-Tricks.

Screen Recording Utilities for macOS

I record quite a few short little videos. Sometimes for use demonstrating bugs or weirdnesses. Sometimes right here for the blog. A lot of times for Instagram or other social media.

Allow me to get SUPER NITPICKY about what I like.

  • Multiple formats. Sometimes you need a GIF. Sometimes you need an MP4. Sometimes you need both. It’s ideal if the software can export as either or both.
  • Easily resizeable recording area. If you need to record the entire screen, fine, but I feel like that’s the job for more full-blown screencasting apps. More often, I need to record a smaller bit of the screen. Ideally, I can drag over the portion I want, but the more control the better.
  • Aspect ratios and saved sizes. Speaking of control, it’s likely I might want a square recording (like if it’s going to Instagram) or I might want a 16:9, a common aspect ratio for TV’s and web video. Ideally, the software helps me get there quickly.
  • Cursor/clicking, or not. Sometimes the point of a video is to demonstrate something, which might require showing the cursor and interactions like clicks. Ideally, that is available but turn-off-able.
  • Editing after recording. The chances of getting a perfect take are rare. More commonly, I’d like to adjust the start and end time of the recording. Since it’s likely the GIF or video is meant to repeat, playing the recording as this is happening is ideal.
  • Configurable shortcuts. I’d ideally like to hit a keyboard command to fire up the app, select a recording area, and go.
  • Audio or no audio. It should be possible to record sound, clear if I am or not, and configurable.
  • Cost. This is just informational as it’s typically a factor. Generally I like to pay for things as it can be a good indicator of quality and support. But as we all known, open source can be incredible, and incentivized companies can do well making free products, too.
  • Retains history. Maybe I need to re-cut it. Maybe I lost my export somehow. Maybe the app weirdly quit. Ideally, I’d like some history so I can go back to some older recordings and export another copy.

GIPHY Capture

The green box there is the area of the screen GIPHY Capture records.

This is a great idea for a company like GIPHY to build, and they’ve done a fine job here. Best of all, I’ve watched it evolve over time to get more and more useful. As a cool bonus feature, you can add captions at specific points in the recording.

My main gripe is the two-window system. The green-box window has recording and history, then a second window for editing and exporting. That alone is no big deal, but when you are editing, you often want to be gone with the green box. But closing the green box means quitting the whole app.

Multiple formats GIF, MP4, or “Batch” which outputs a folder with both.
Easily resizeable recording area Position and size the green box over the area you want to record.
Aspect ratios and saved sizes No aspect ratios, but you can specifiy pixel width/height and it will save your recently used ones. A bit hidden, you have to click the pixel dimensions in the lower right to access it.
Cursor/clicking Recording the cursor is on/off setting. If on, it adds a circle around the cursor when you click.
Editing after recording Handles at the beginning and end of the timeline allow you to drag them inward to crop the clip. Very nicely handled (get it?) — I think this might be the best take on editing.
File size control You can choose from a handful of options for both pixel size and frame rate to control size.

Not as fine-grained as you might want but likely fits most needs.

Configurable shortcuts When the app is open, you can set a letter or number as a key command to start/stop recording.
Audio or no audio No audio recording at all
Cost Free
Retains history I’m not sure how far back the history goes (it’s a bit hard to navigate beyond what you can see) but the lower bar of the green recording window gives history access to the last few very easily. Batch exporting is a clever feature. Sometimes I really do need both types (GIF and video), and that need is likely to increase.


I think Kap is my favorite one. At least it is today. It’s quite polished, and also open source, perhaps as a bit of marketing for the agency it comes from.

Kap is at version 2.0 right now, and I quite like it. I had 1.0 and aborted pretty quickly. I can’t remember why exactly, but it didn’t measure up to other options. Version 2.0 is perhaps best-of-breed. I’m a fan of the fact that it’s a menu bar app, so it is ready all the time instead of something I need to launch.

Its fancy bonus feature is installable export locations, like uploading to Cloudinary or S3.

The keyboard shortcut is one thing that (and this is weirdly unique to me) really bugs me. It actually keeps me from having it open all the time, because Command-Shift-5 is CodePen’s command for re-running, which I use all the time. Configurability, please!

Multiple formats The most formats! GIF and MP4, but also WebM and APNG. Cool, but you can only export one at a time.
Easily resizeable recording area Clicking the record button gives you little black-white dashed lines you position and size over the recording area. If GIPHY Capture’s green screen is papa bear (too much), this is mama bear (too little). There is probably a just right baby bear in there somewhere.
Aspect ratios and saved sizes Sizing is a first-class citizen here, giving you a dropdown for aspect ratio or controls for exact sizes (that it remembers).
Cursor/clicking Under preferences, you can flip cursor recording on and off (and separately from click highlighting).
Editing after recording Drag handles from the start or end inward to edit.
File size control It’s a big strange. There is an FPS control buried in settings to adjust the frame rate, but then on the editing screen before you export, you only get to pick between 30 and 15, so it’s not clear what happens if you’ve adjusted it in settings to something other than those.
Configurable shortcuts Weirdly, it’s Command-Shift-5, which it doesn’t tell you, allow you to turn off, or configure.
Audio or no audio One click to turn on and off right before you record or after you record.
Cost Free and open source.
Retains history No history, but warns you before you close an editing window so you don’t accidently lose recordings.


Old school! LICEcap is the app that opened my eyes to the idea that these apps were even a thing. Perhaps the first of its kind.

Multiple formats GIF only
Easily resizeable recording area The empty frame window might be the most clear UI out of all of them.
Aspect ratios and saved sizes Neither, but it is easy to manually resize or type in pixel dimensions manually
Cursor/clicking You decide if you want it right before you record.
Editing after recording None
File size control You can choose the Droplr
Menu bar app

Droplr absolutely has the power to record quick screencasts, but it’s much more limited than these others. What it does offer is a very quick way to get your screencasts up onto the web in a permanent and shareable way very quickly. If that’s the most important thing to you, you’d be in good hands.

Multiple formats GIF or MOV
Easily resizeable recording area Every time you record you have to drag over the area you want to record.
Aspect ratios and saved sizes Easy to select a recording area, but it doesn’t save sizes, tell you the dimensions of your selected area, or help with aspect ratios.
Cursor/clicking Automatically includes cursor and click highlighting.
Editing after recording None. You just choose GIF or MOV and it auto-uploads it. The ability to at least save locally before uploading would be nice.
File size control None
Configurable shortcuts You can pick a custom keyboard command for screencasts, along with different key commands for everythinge else Droplr does.
Audio or no audio As you upload, it gives the impression that videos automatically include sound. But, you can turn off audio recording in preferences.
Cost Freemium. If you need unlimited length screen recordings, it’s $8.29/month.
Retains history Yep, through the Droplr service, you’ll have a complete history of all recordings.


Like Droplr, CloudApp will help you record a screencast, but it’s all about getting that screencast uploaded to their service so you can share it from there. That can be awfully handy, but also get in the way when you just want to work locally. You can set a preference to save the GIF and movie record locally, but it’s a PRO feature.

Multiple formats GIF or MOV, which you pick before you record.
Easily resizeable recording area Drag over the area you want.
Aspect ratios and saved sizes Also like Droplr, you drag over the area you want, but it doesn’t tell you the dimensions as you are doing it, allow to specify or adjust that size with numbers or help with aspect ratios.
Cursor/clicking Option in preferences.
Editing after recording No
File size control In preferences, you can configure GIF Gifox

Gifox was unknown to me before I started looking around for this post. It’s pretty great! Very modern. Lots of options. Fairly priced. Plus a few pretty neat features.

Multiple formats Only GIF, which is unfortunate as it might be this app’s only weakness.
Easily resizeable recording area Drag to record an area (helps you with coordinates and sizing) or record specific windows (nice touch).
Aspect ratios and saved sizes No aspect ratios, but it does allow you to lock the size so that subsequent recordings open up at exactly the same size.
Cursor/clicking Option in settings.
Editing after recording None
File size control In settings you can control recording and playback Screenflow

Screenflow is really beefy screencasting software. All the stuff we’ve looked at so far is for little tiny quicky stuff. Screenflow is for long-form, edited, fancy screencasts. You can use it for little stuff, but it would be overkill and all the control would probably get in the way more than help. But if you need lots of control, it’s fantastic.

Multiple formats Just video.
Easily resizeable recording area Screenflow turns this on it’s head. Generally you record the entire screen, then during editing, you crop down to what you need. Newer versions let you scope down the recording area before you record, but the old paradigm is still there and probably a smart way to work in general.
Aspect ratios and saved sizes Lots of control. It defaults to resizing as an aspect ratio when you crop after recording, but you can change it with hard pixel values if you wish, or choose from presets.
Cursor/clicking Loads of control here. As you’re editing, you can add action points that allow you to focus on the cursor with various effects, like graying out the rest of the screen.
Editing after recording This is the main point of Screenflow.
File size control Lots of exporting control for size, speed, and quality.
Configurable shortcuts Massive set of configurable keyboard commands.
Audio or no audio You choose what audio sources you want to record when you record. You can always remove those tracks during editing, or edit the audio just as you do the video.
Cost Starts at $129.99.
Retains history Only what you save.

The Graveyard?

  • Screeny. Looks pretty nice, but also looks like it hasn’t been touched in five years and I didn’t wanna spend $14.99 when there seems to be a lot of good modern alternatives.
  • Recordit. Looks pretty similar to some of these others — notably CloudApp and Droplr — as it has a hosted service. But also sorta looks limited and abandoned.
  • GifGrabber. Looks pretty good and it’s free! Just also feels a bit abandoned and only does GIF.

The post Screen Recording Utilities for macOS appeared first on CSS-Tricks.

Creating a Parking Game With the HTML Drag and Drop API

Among the many JavaScript APIs added in HTML5 was Drag and Drop (we’ll refer to it as DnD in this article) which brought native DnD support to the browser, making it easier for developers to implement this interactive feature into applications. The amazing thing that happens when features become easier to implement is that people start making all kinds of silly, impractical things with it, like the one we’re making today: a parking game!

DnD requires only a few things to work:

  • Something to drag
  • Somewhere to drop
  • JavaScript event handlers on the target to tell the browser it can drop

We’re going to start by creating our draggables.


Both <img> and <a>(with the href attribute set) elements are draggable by default. If you want to drag a different element, you’ll need to set the draggable attribute to true.

We’ll start with the HTML that sets up the images for our four vehicles: fire truck, ambulance, car and bicycle.

<ul class="vehicles"> <li> <!-- Fire Truck --> <!-- <code>img<code> elements don't need a <code>draggable<code> attribute like other elements --> <img id="fire-truck" alt="fire truck" src="https://cdn.glitch.com/20f985bd-431d-4807-857b-e966e015c91b%2Ftruck-clip-art-fire-truck4.png?1519011787956"/> </li> <li> <!-- Ambulance --> <img id="ambulance" alt="ambulance" src="https://cdn.glitch.com/20f985bd-431d-4807-857b-e966e015c91b%2Fambulance5.png?1519011787610"> </li> <li> <!-- Car --> <img id="car" alt="car" src="https://cdn.glitch.com/20f985bd-431d-4807-857b-e966e015c91b%2Fcar-20clip-20art-1311497037_Vector_Clipart.png?1519011788408"> </li> <li> <!-- Bike --> <img id="bike" alt="bicycle" src="https://cdn.glitch.com/20f985bd-431d-4807-857b-e966e015c91b%2Fbicycle-20clip-20art-bicycle3.png?1519011787816"> </li>

Since images are draggable by default, you’ll see dragging any one of them creates a ghost image.

Just adding a draggable attribute to an element that’s not an image or link is really all you need to make an element draggable in most browsers. To make elements draggable in all browsers, you need to define some event handlers. They are also useful for adding extra functionality like a border if an element is being dragged around or a sound if it stops being dragged. For these, you’re going to need some drag event handlers, so let’s look at those.

Drag Events

There are three drag-related events you can listen for but we’re only going to use two: dragstart and dragend.

  • dragstart – Triggered as soon as we start dragging. This is where we can define the drag data and the drag effect.
  • dragend – Triggered when a draggable element is dropped. This event is generally fired right after the drop zone’s drop event.

We’ll cover what the drag data and the drag effect is shortly.

let dragged; // Keeps track of what's being dragged - we'll use this later! function onDragStart(event) { let target = event.target; if (target && target.nodeName === 'IMG') { // If target is an image dragged = target; event.dataTransfer.setData('text', target.id); event.dataTransfer.dropEffect = 'move'; // Make it half transparent when it's being dragged event.target.style.opacity = .3; }
} function onDragEnd(event) { if (event.target && event.target.nodeName === 'IMG') { // Reset the transparency event.target.style.opacity = ''; // Reset opacity when dragging ends dragged = null; }
} // Adding event listeners
const vehicles = document.querySelector('.vehicles');
vehicles.addEventListener('dragstart', onDragStart);
vehicles.addEventListener('dragend', onDragEnd);

There are a couple of things happening in this code:

  • We are defining the drag data. Each drag event has a property called dataTransfer that stores the event’s data. You can use the setData(type, data) method to add a dragged item to the drag data. We’re storing the dragged image’s ID as type 'text' in line 7.
  • We’re storing the element being dragged in a global variable. I know, I know. Global is dangerous for scoping but here’s why we do it: although you can store the dragged item using setData, you can’t retrieve it using event.dataTransfer.getData() in all browsers (except Firefox) because the drag data is protected mode. You can read more about it here. I wanted to mention defining the drag data just so you know about it.
  • We’re setting the dropEffect to move. The dropEffect property is used to control the feedback the user is given during a drag and drop operation. For example, it changes which cursor the browser displays while dragging. There are three effects: copy, move and link.
    • copy – Indicates that the data being dragged will be copied from its source to the drop location.
    • move – Indicates that the data being dragged will be moved.
    • link – Indicates that some form of relationship will be created between the source and drop locations.

Now we have draggable vehicles but nowhere to drop them:

See the Pen 1 – Can you park here? by Omayeli Arenyeka (@yelly) on CodePen.


By default, when you drag an element, only form elements such as <input> will be able to accept it as a drop. We’re going to contain our “dropzone” in a <section> element, so we need to add drop event handlers so it can accept drops just like a form element.

First, since it’s an empty element we’re going to need to set a width, height and background color on it so we can see it on screen.

These are the parameters we have available for drop events:

  • dragenter – Triggered at the moment a draggable item enters a droppable area. At least 50% of the draggable element has to be inside the drop zone.
  • dragover – The same as dragenter but it is called repeatedly while the draggable item is within the drop zone.
  • dragleave – Triggered once a draggable item has moved away from a drop zone.
  • drop – Triggered when the draggable item has been released and the drop area agrees to accept the drop.
function onDragOver(event) { // Prevent default to allow drop event.preventDefault();
} function onDragLeave(event) { event.target.style.background = '';
} function onDragEnter(event) { const target = event.target; if (target) { event.preventDefault(); // Set the dropEffect to move event.dataTransfer.dropEffect = 'move' target.style.background = '#1f904e'; }
} function onDrop(event) { const target = event.target; if ( target) { target.style.backgroundColor = ''; event.preventDefault(); // Get the id of the target and add the moved element to the target's DOM dragged.parentNode.removeChild(dragged); dragged.style.opacity = ''; target.appendChild(dragged); }
} const dropZone = document.querySelector('.drop-zone');
dropZone.addEventListener('drop', onDrop);
dropZone.addEventListener('dragenter', onDragEnter);
dropZone.addEventListener('dragleave', onDragLeave);
dropZone.addEventListener('dragover', onDragOver);

If you’re wondering why we keep calling event.preventDefault() it’s because by default the browser assumes any target is not a valid drop target. This isn’t true all the time for all browsers but it’s better to be safe than sorry! Calling preventDefault() on the dragenter, dragover and drop events, informs the browser that the current target is a valid drop target.

Now, we have a simple drag and drop application!

See the Pen 2 – Can you park here? by Omayeli Arenyeka (@yelly) on CodePen.

It’s fun, but not quite as frustrating as parking. We have to create some rules to make that happen.

Rules and Validation

I came up with some random parking rules, and I’d encourage you to create some of your own. Parking signs usually have days and times you can park as well as what types of vehicles are allowed to park at that moment in time. When we were creating our draggable objects, we had four vehicles: an ambulance, a fire truck, a regular car and a bicycle. So, we’re going to create rules for them.

  1. Ambulance parking only: Monday through Friday, 9pm to 3am.
  2. Fire truck parking only: All day during the weekend.
  3. Regular car parking: Monday through Friday, 3am to 3pm.
  4. Bicycle parking: Monday through Friday, 3pm to 9pm.

Now, we translate these rules to code. We’re going to be using two libraries to handle time and ranges: Moment and Moment-range.

The scripts are already available in Codepen to add to any new demo, but if you are developing outside of Codepen you can copy or link them up from here:

<script defer src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/3.1.1/moment-range.js"></script>

Then, we create an object to store all the parking rules.

window['moment-range'].extendMoment(moment); // The array of weekdays
const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
const parkingRules = { ambulance: { // The ambulance can only park on weekdays... days: weekdays, // ...from 9pm to 3am (the next day) times: createRange(moment().set('hour', 21), moment().add(1, 'day').set('hour', 3)) }, 'fire truck': { // The fire truck can obnly park on Saturdays and Sundays, but all day days: ['Saturday', 'Sunday'] }, car: { // The car can only park on weekdays... days: weekdays, // ...from 3am - 3pm (the same day) times: createRange(moment().set('hour', 3), moment().set('hour', 15)) }, bicycle: { // The car can only park on weekdays... days: weekdays, // ...from 3pm - 9pm (the same day) times: createRange(moment().set('hour', 15), moment().set('hour', 21)) }
}; function createRange(start, end) { if (start && end) { return moment.range(start, end); }

Each vehicle in the parkingRules object has a days property with an array of days it can park and a times property that is a time range. To get the current time using Moment, call moment(). To create a range using Moment-range, pass a start and end time to the moment.range function.

Now, in the onDragEnter and onDrop event handlers we defined earlier, we add some checks to make sure a vehicle can park. Our alt attribute on the img tag is storing the type of vehicle so we pass that to a canPark method which will return if the car can be parked. We also added visual cues (change in background) to tell the user whether a vehicle can be parked or not.

function onDragEnter(event) { const target = event.target; if (dragged && target) { const vehicleType = dragged.alt; // e.g bicycle, ambulance if (canPark(vehicleType)) { event.preventDefault(); // Set the dropEffect to move event.dataTransfer.dropEffect = 'move'; /* Change color to green to show it can be dropped /* target.style.background = '#1f904e'; } else { /* Change color to red to show it can't be dropped. Notice we * don't call event.preventDefault() here so the browser won't * allow a drop by default */ target.style.backgroundColor = '#d51c00'; } }
} function onDrop(event) { const target = event.target; if (target) { const data = event.dataTransfer.getData('text'); const dragged = document.getElementById(data); const vehicleType = dragged.alt; target.style.backgroundColor = ''; if (canPark(vehicleType)) { event.preventDefault(); // Get the ID of the target and add the moved element to the target's DOM dragged.style.opacity = ''; target.appendChild(dragged); } }

Then, we create the canPark method.

function getDay() { return moment().format('dddd'); // format as 'monday' not 1
} function getHours() { return moment().hour();
} function canPark(vehicle) { /* Check the time and the type of vehicle being dragged * to see if it can park at this time */ if (vehicle && parkingRules[vehicle]) { const rules = parkingRules[vehicle]; const validDays = rules.days; const validTimes = rules.times; const curDay = getDay(); if (validDays) { /* If the current day is included on the parking days for the vehicle * And if the current time is within the range */ return validDays.includes(curDay) && (validTimes ? validTimes.contains(moment()) : true); /* Moment.range has a contains function that checks * to see if your range contains a moment. https://github.com/rotaready/moment-range#contains */ } } return false;

Now, only cars that are allowed to park can park. Lastly, we add the rules to the screen and style it.

Here’s the final result:

See the Pen 3 – Can you park here? by Omayeli Arenyeka (@yelly) on CodePen.

There are lots of ways this could be improved:

  • Auto-generate the HTML for the rules list from the parkingRules object!
  • Add some sound effects!
  • Add ability to drag back vehicles to original point without a page refresh.
  • All those pesky global variables.

But I’ll let you handle that.

If you’re interested in learning more about the DnD API and some critiques of it, here’s some good reading:

  • WHATWG Specification
  • Working with HTML5 Drag-and-Drop – Pro HTML5 Programming, Chapter 9, by Jen Simmons
  • Accessible Drag and Drop Using WAI-ARIA – Accessibility considerations from Dev.Opera
  • Native HTML5 Drag and Drop – HTML5 Rocks tutorial
  • The HTML5 drag and drop disaster – QuirksMode post with helpful context on the DnD module implementation

The post Creating a Parking Game With the HTML Drag and Drop API appeared first on CSS-Tricks.

What Houdini Means for Animating Transforms

I’ve been playing with CSS transforms for over five years and one thing that has always bugged me was that I couldn’t animate the components of a transform chain individually. This article is going to explain the problem, the old workaround, the new magic Houdini solution and, finally, will offer you a feast of eye candy through better looking examples than those used to illustrate concepts.

The Problem

In order to better understand the issue at hand, let’s consider the example of a box we move horizontally across the screen. This means one div as far as the HTML goes:

<div class="box"></div>

The CSS is also pretty straightforward. We give this box dimensions, a background and position it in the middle horizontally with a margin.

$d: 4em; .box { margin: .25*$d auto; width: $d; height: $d; background: #f90;

See the Pen by thebabydino (@thebabydino) on CodePen.

Next, with the help of a translation along the x axis, we move it by half a viewport (50vw) to the left (in the negative direction of the x axis, the positive one being towards the right):

transform: translate(-50vw);

See the Pen by thebabydino (@thebabydino) on CodePen.

Now the left half of the box is outside the screen. Decreasing the absolute amount of translation by half its edge length puts it fully within the viewport while decreasing it by anything more, let’s say a full edge length (which is $d or 100%—remember that % values in translate() functions are relative to the dimensions of the element being translated), makes it not even touch the left edge of the viewport anymore.

transform: translate(calc(-1*(50vw - 100%)));

See the Pen by thebabydino (@thebabydino) on CodePen.

This is going to be our initial animation position.

We then create a set of @keyframes to move the box to the symmetrical position with respect to the initial one with no translation and reference them when setting the animation:

$t: 1.5s; .box { /* same styles as before */ animation: move $t ease-in-out infinite alternate;
} @keyframes move { to { transform: translate(calc(50vw - 100%)); }

This all works as expected, giving us a box that moves from left to right and back:

See the Pen by thebabydino (@thebabydino) on CodePen.

But this is a pretty boring animation, so let’s make it more interesting. Let’s say we want the box to be scaled down to a factor of .1 when it’s in the middle and have its normal size at the two ends. We could add one more keyframe:

50% { transform: scale(.1); }

The box now also scales (demo), but, since we’ve added an extra keyframe, the timing function is not applied for the whole animation anymore—just for the portions in between keyframes. This makes our translation slow in the middle (at 50%) as we now also have a keyframe there. So we need to tweak the timing function, both in the animation value and in the @keyframes. In our case, since we want to have an ease-in-out overall, we can split it into one ease-in and one ease-out.

.box { animation: move $t ease-in infinite alternate;
} @keyframes move { 50% { transform: scale(.1); animation-timing-function: ease-out; } to { transform: translate(calc(50vw - 100%)); }

See the Pen by thebabydino (@thebabydino) on CodePen.

Now all works fine, but what if we wanted different timing functions for the translation and scaling? The timing functions we’ve set mean the animation is slower at the beginning, faster in the middle and then slower again at the end. What if we wanted this to apply just to the translation, but not to the scale? What if we wanted the scaling to happen fast at the beginning, when it goes from 1 towards .1, slow in the middle when it’s around .1 and then fast again at the end when it goes back to 1?

SVG illustration. Shows the timeline, highlighting the 0%, 50% and 100% keyframes. At 0%, we want the translation to start slowly, but the scaling to start fast. At 50%, we want the translation to be at its fastest, while the scaling would be at its slowest. At 100%, the translation ends slowly, while the scaling ends fast.
The animation timeline (live).

Well, it’s just not possible to set different timing functions for different transform functions in the same chain. We cannot make the translation slow and the scaling fast at the beginning or the other way around in the middle. At least, not while what we animate is the transform property and they’re part of the same transform chain.

The Old Workaround

There are of course ways of going around this issue. Traditionally, the solution has been to split the transform (and consequently, the animation) over multiple elements. This gives us the following structure:

<div class="wrap"> <div class="box"></div>

We move the width property on the wrapper. Since div elements are block elements by default, this will also determine the width of its .box child without us having to set it explicitly. We keep the height on the .box however, as the height of a child (the .box in this case) also determines the height of its parent (the wrapper in this case).

We also move up the margin, transform and animation properties. In addition to this, we switch back to an ease-in-out timing function for this animation. We also modify the move set of @keyframes to what it was initially, so that we get rid of the scale().

.wrap { margin: .25*$d calc(50% - #{.5*$d}); width: $d; transform: translate(calc(-1*(50vw - 100%))); animation: move $t ease-in-out infinite alternate;
} @keyframes move { to { transform: translate(calc(50vw - 100%)); }

We create another set of @keyframes which we use for the actual .box element. This is an alternating animation of half the duration of the one producing the oscillatory motion.

.box { height: $d; background: #f90; animation: size .5*$t ease-out infinite alternate;
} @keyframes size { to { transform: scale(.1); } }

We now have the result we wanted:

See the Pen by thebabydino (@thebabydino) on CodePen.

This is a solid workaround that doesn’t add too much extra code, not to mention the fact that, in this particular case, we don’t really need two elements, we could do with just one and one of its pseudo-elements. But if our transform chain gets longer, we have no choice but to add extra elements. And, in 2018, we can do better than that!

The Houdini Solution

Some of you may already know that CSS variables are not animatable (and I guess anyone who didn’t just found out). If we try to use them in an animation, they just flip from one value to the other when half the time in between has elapsed.

Consider the initial example of the oscillating box (no scaling involved). Let’s say we try to animate it using a custom property --x:

.box { /* same styles as before */ transform: translate(var(--x, calc(-1*(50vw - #{$d})))); animation: move $t ease-in-out infinite alternate
} @keyframes move { to { --x: calc(50vw - #{$d}) } }

Sadly, this just results in a flip at 50%, the official reason being that browsers cannot know the type of the custom property (which doesn’t make sense to me, but I guess that doesn’t really matter).

See the Pen by thebabydino (@thebabydino) on CodePen.

But we can forget about all of this because now Houdini has entered the picture and we can register such custom properties so that we explicitly give them a type (the syntax).

For more info on this, check out the talk and slides by Serg Hospodarets.

CSS.registerProperty({ name: '--x', syntax: '<length>', initialValue: 0

We’ve set the initialValue to 0, because we have to set it to something and that something has to be a computationally independent value—that is, it cannot depend on anything we can set or change in the CSS and, given the initial and final translation values depend on the box dimensions, which we set in the CSS, calc(-1*(50vw - 100%)) is not valid here. It doesn’t even work to set --x to calc(-1*(50vw - 100%)), we need to use calc(-1*(50vw - #{$d})) instead.

$d: 4em;
$t: 1.5s; .box { margin: .25*$d auto; width: $d; height: $d; --x: calc(-1*(50vw - #{$d})); transform: translate(var(--x)); background: #f90; animation: move $t ease-in-out infinite alternate;
} @keyframes move { to { --x: calc(50vw - #{$d}); } }
Animated gif. Shows a square box oscillating horizontally from left to right and back. The motion is slow at the left and right ends and faster in the middle.
The simple oscillating box we get using the new method (live demo, needs Houdini support).

For now, this only works in Blink browsers behind the Experimental Web Platform features flag. This can be enabled from chrome://flags (or, if you’re using Opera, opera://flags):

Screenshot showing the Experimental Web Platform features flag being enabled in Chrome.
The Experimental Web Platform features flag enabled in Chrome.

In all other browsers, we still see the flip at 50%.

Applying this to our oscillating and scaling demo means we introduce two custom properties we register and animate—one is the translation amount along the x axis (--x) and the other one is the uniform scaling factor (--f).

CSS.registerProperty({ /* same as before */ }); CSS.registerProperty({ name: '--f', syntax: '<number>', initialValue: 1

The relevant CSS is as follows:

.box { --x: calc(-1*(50vw - #{$d})); transform: translate(var(--x)) scale(var(--f)); animation: move $t ease-in-out infinite alternate, size .5*$t ease-out infinite alternate;
} @keyframes move { to { --x: calc(50vw - #{$d}); } } @keyframes size { to { --f: .1 } }
Animated gif. Shows the same oscillating box from before now also scaling down to 10% when it's right in the middle. The scaling is fast at the beginning and the end and slow in the middle.
The oscillating and scaling with the new method (live demo, needs Houdini support).

Better Looking Stuff

A simple oscillating and scaling square isn’t the most exciting thing though, so let’s see nicer demos!

Screenshots of the two demos we dissect here. Left: a rotating wavy rainbow grid of cubes. Right: bouncing square.
More interesting examples. Left: rotating wavy grid of cubes. Right: bouncing square.

The 3D version

Going from 2D to 3D, the square becomes a cube and, since just one cube isn’t interesting enough, let’s have a whole grid of them!

We consider the body to be our scene. In this scene, we have a 3D assembly of cubes (.a3d). These cubes are distributed on a grid of nr rows and nc columns:

- var nr = 13, nc = 13;
- var n = nr*nc; .a3d while n-- .cube - var n6hedron= 6; // cube always has 6 faces while n6hedron-- .cube__face

The first thing we do is a few basic styles to create a scene with a perspective, put the whole assembly in the middle and put each cube face into its place. We won’t be going into the details of how to build a CSS cube because I’ve already dedicated a very detailed article to this topic, so if you need a recap, check that one out!

The result so far can be seen below – all the cubes stacked up in the middle of the scene:

Screenshot. Shows all cubes (as wireframes) in the same position in the middle of the scene, making it look as if there's only one wireframe.
All the cubes stacked up in the middle (live demo).

For all these cubes, their front half is in front of the plane of the screen and their back half is behind the plane of the screen. In the plane of the screen, we have a square section of our cube. This square is identical to the ones representing the cube faces.

See the Pen by thebabydino (@thebabydino) on CodePen.

Next, we set the column (--i) and row (--j) indices on groups of cubes. Initially, we set both these indices to 0 for all cubes.

.cube { --i: 0; --j: 0;

Since we have a number of cubes equal to the number of columns (nc) on every row, we then set the row index to 1 for all cubes after the first nc ones. Then, for all cubes after the first 2*nc ones, we set the row index to 2. And so on, until we’ve covered all nr rows:

style | .cube:nth-child(n + #{1*nc + 1}) { --j: 1 } | .cube:nth-child(n + #{2*nc + 1}) { --j: 2 } //- and so on | .cube:nth-child(n + #{(nr - 1)*nc + 1}) { --j: #{nr - 1} }

We can compact this in a loop:

style - for(var i = 1; i < nr; i++) { | .cube:nth-child(n + #{i*nc + 1}) { --j: #{i} } -}

Afterwards, we move on to setting the column indices. For the columns, we always need to skip a number of cubes equal to nc - 1 before we encounter another cube with the same index. So, for every cube, the nc-th cube after it is going to have the same index and we’re going to have nc such groups of cubes.

(We only need to set the index to the last nc - 1, because all cubes have the column index set to 0 initially, so we can skip the first group containing the cubes for which the column index is 0 – no need to set --i again to the same value it already has.)

style | .cube:nth-child(#{nc}n + 2) { --i: 1 } | .cube:nth-child(#{nc}n + 3) { --i: 2 } //- and so on | .cube:nth-child(#{nc}n + #{nc}) { --i: #{nc - 1} }

This, too, can be compacted in a loop:

style - for(var i = 1; i < nc; i++) { | .cube:nth-child(#{nc}n + #{i + 1}) { --i: #{i} } -}

Now that we have all the row and column indices set, we can distribute these cubes on a 2D grid in the plane of the screen using a 2D translate() transform, according to the illustration below, where each cube is represented by its square section in the plane of the screen and the distances are measured in between transform-origin points (which are, by default, at 50% 50% 0, so dead in the middle of the square cube sections from the plane of the screen):

SVG illustration. Shows how to create a basic grid of square, vertical cube sections with nc columns and nr rows starting from the position of the top left item. The top left item is on the first column (of index <code>0</code>) and on the first row (of index <code>0</code>). All items on the second column (of index <code>1</code>) are offset horizontally by and edge length. All items on the third column (of index <code>2</code>) are offset horizontally by two edge lengths. In general, all items on the column of index <code>i</code> are offset horizontally by <code>i</code> edge lengths. All items on the last column (of index <code>nc - 1</code>) are offset horizontally by <code>nc - 1</code> edge lengths. All items on the second row (of index <code>1</code>) are offset vertically by and edge length. All items on the third row (of index <code>2</code>) are offset vertically by two edge lengths. In general, all items on the row of index <code>j</code> are offset vertically by <code>j</code> edge lengths. All items on the last row (of index <code>nr - 1</code>) are offset vertically by <code>nr - 1</code> edge lengths.”/><figcaption>How to create a basic grid starting from the position of the top left item (live).</figcaption></figure>
<pre rel=/* $l is the cube edge length */ .cube { /* same as before */ --x: calc(var(--i)*#{$l}); --y: calc(var(--j)*#{$l}); transform: translate(var(--x), var(--y)); }

This gives us a grid, but it’s not in the middle of the screen.

Screenshot. Shows the grid with nc columns and nr rows, with cubes repersented as wireframes. The midpoint of the top left cube of the rectangular grid is dead in the middle of the screen..
The grid, having the midpoint of the top left cube in the middle of the screen (live demo).

Right now, it’s the central point of the top left cube that’s in the middle of the screen, as highlighted in the demo above. What we want is for the grid to be in the middle, meaning that we need to shift all cubes left and up (in the negative direction of both the x and y axes) by the horizontal and vertical differences between half the grid dimensions (calc(.5*var(--nc)*#{$l}) and calc(.5*var(--nr)*#{$l}), respectively) and the distances between the top left corner of the grid and the midpoint of the top left cube’s vertical cross-section in the plane of the screen (these distances are each half the cube edge, or .5*$l).

The difference between the position of the grid midpoint and the top left item midpoint (live).

Subtracting these differences from the previous amounts, our code becomes:

.cube { /* same as before */ --x: calc(var(--i)*#{$l} - (.5*var(--nc)*#{$l} - .5*#{$l})); --y: calc(var(--j)*#{$l} - (.5*var(--nr)*#{$l} - .5*#{$l}));

Or even better:

.cube { /* same as before */ --x: calc((var(--i) - .5*(var(--nc) - 1))*#{$l})); --y: calc((var(--j) - .5*(var(--nr) - 1))*#{$l}));

We also need to make sure we set the --nc and --nr custom properties:

- var nr = 13, nc = 13;
- var n = nr*nc; //- same as before
.a3d(style=`--nc: ${nc}; --nr: ${nr}`) //- same as before

This gives us a grid that’s in the middle of the viewport:

Screenshot. Shows a grid of cube wireframes right in the middle.
The grid is now in the middle (live).

We’ve also made the cube edge length $l smaller so that the grid fits within the viewport.

Alternatively, we can go for a CSS variable --l instead so that we can control the edge length depending on the number of columns and rows. The first step here is setting the maximum of the two to a --nmax variable:

- var nr = 13, nc = 13;
- var n = nr*nc; //- same as before
.a3d(style=`--nc: ${nc}; --nr: ${nr}; --max: ${Math.max(nc, nr)}`) //- same as before

Then, we set the edge length (--l) to something like 80% (completely arbitrary value) of the minimum viewport dimension over this maximum (--max):

.cube { /* same as before */ --l: calc(80vmin/var(--max));

Finally, we update the cube and face transforms, the face dimensions and margin to use --l instead of $l:

.cube { /* same as before */ --l: calc(80vmin/var(--max)); --x: calc((var(--i) - .5*(var(--nc) - 1))*var(--l)); --y: calc((var(--j) - .5*(var(--nr) - 1))*var(--l)); &__face { /* same as before */ margin: calc(-.5*var(--l)); width: var(--l); height: var(--l); transform: rotate3d(var(--i), var(--j), 0, calc(var(--m, 1)*#{$ba4gon})) translatez(calc(.5*var(--l))); }

Now we have a nice responsive grid!

Animated gif. Shows the previously created grid scaling with the viewport.
The grid is now in the middle and responsive such that it always fits within the viewport (live).

But it’s an ugly one, so let’s turn it into a pretty rainbow by making the color of each cube depend on its column index (--i):

.cube { /* same as before */ color: hsl(calc(var(--i)*360/var(--nc)), 65%, 65%);
Screenshot. The assembly wireframe has now a rainbow look, with every column of cubes having a different hue.
The rainbow grid (live demo).

We’ve also made the scene background dark so that we have better contrast with the now lighter cube edges.

To spice things up even further, we add a row rotation around the y axis depending on the row index (--j):

.cube { /* same as before */ transform: rotateY(calc(var(--j)*90deg/var(--nr))) translate(var(--x), var(--y));
Screenshot. The assembly wireframe now appears twisted, with every row being rotated at a different angle, increasing from top to bottom.
The twisted grid (live demo).

We’ve also decreased the cube edge length --l and increased the perspective value in order to allow this twisted grid to fit in.

Now comes the fun part! For every cube, we animate its position back and forth along the z axis by half the grid width (we make the translate() a translate3d() and use an additional custom property --z that goes between calc(.5*var(--nc)*var(--l)) and calc(-.5*var(--nc)*var(--l))) and its size (via a uniform scale3d() of factor --f that goes between 1 and .1). This is pretty much the same thing we did for the square in our original example, except the motion now happens along the z axis, not along the x axis and the scaling happens in 3D, not just in 2D.

$t: 1s; .cube { /* same as before */ --z: calc(var(--m)*.5*var(--nc)*var(--l)); transform: rotateY(calc(var(--j)*90deg/var(--nr))) translate3d(var(--x), var(--y), var(--z)) scale3d(var(--f), var(--f), var(--f)); animation: a $t ease-in-out infinite alternate; animation-name: move, zoom; animation-duration: $t, .5*$t;
} @keyframes move { to { --m: -1 } } @keyframes zoom { to { --f: .1 } }

This doesn’t do anything until we register the multiplier --m and the scaling factor --f to give them a type and an initial value:

CSS.registerProperty({ name: '--m', syntax: '<number>', initialValue: 1
}); CSS.registerProperty({ name: '--f', syntax: '<number>', initialValue: 1
Animated gif. Every cube now moves back and forth along its own z axis (post row rotation), between half a grid width behind its xOy plane and half a grid width in front of its xOy plane. Each cube also scales along all three axes, going from its initial size to a tenth of it along each axis and then back to its initial size.
The animated grid (live demo, needs Houdini support).

At this point, all cubes animate at the same time. To make things more interesting, we add a delay that depends on both the column and row index:

animation-delay: calc((var(--i) + var(--j))*#{-2*$t}/(var(--nc) + var(--nr)));
The waving grid effect (live).

The final touch is to add a rotation on the 3D assembly:

.a3d { top: 50%; left: 50%; animation: ry 8s linear infinite;
} @keyframes ry { to { transform: rotateY(1turn); } }

We also make the faces opaque by giving them a black background and we have the final result:

Animated gif. Now the cube faces are opaque (we've given them a black background) whole assembly rotates around its y axis, making the animation more interesting.
The final result (live demo, needs Houdini support).

The performance for this is pretty bad, as it can be seen from the GIF recording above, but it’s still interesting to see how far we can push things.

Hopping Square

I came across the original in a comment to another article and, as soon as I saw the code, I thought it was the perfect candidate for a makeover using some Houdini magic!

Let’s start by understanding what is happening in the original code.

In the HTML, we have nine divs.

<div class="frame"> <div class="center"> <div class="down"> <div class="up"> <div class="squeeze"> <div class="rotate-in"> <div class="rotate-out"> <div class="square"></div> </div> </div> </div> </div> </div> <div class="shadow"></div> </div>

Now, this animation is a lot more complex than anything I could ever come up with, but, even so, nine elements seems to be overkill. So let’s take a look at the CSS, see what they’re each used for and see how much we can simplify the code in preparation for switching to the Houdini-powered solution.

Let’s start with the animated elements. The .down and .up elements each have an animation related to moving the square vertically:

/* original */
.down { position: relative; animation: down $duration ease-in infinite both; .up { animation: up $duration ease-in-out infinite both; /* the rest */ }
} @keyframes down { 0% { transform: translateY(-100px); } 20%, 100% { transform: translateY(0); }
} @keyframes up { 0%, 75% { transform: translateY(0); } 100% { transform: translateY(-100px); }

With @keyframes and animations on both elements having the same duration, we can pull off a make-one-out-of-two trick.

In the case of the first set of @keyframes, all the action (going from -100px to 0) happens in the [0%, 20%] interval, while, in the case of the second one, all the action (going from 0 to -100px) happens in the [75%, 100%] interval. These two intervals don’t intersect. Because of this and because both animations have the same duration we can add up the translation values at each keyframe.

  • at 0%, we have -100px from the first set of @keyframes and 0 from the second, which gives us -100px
  • at 20%, we have 0 from the first set of @keyframes and 0 from the second (as we have 0 for any frame from 0% to 75%), which gives us 0
  • at 75%, we have 0 from the first set of @keyframes (as we have 0 for any frame from 20% to 100%) and 0 from the second, which gives us 0
  • at 100%, we have 0 from the first set of @keyframes and -100px from the second, which gives us -100px

Our new code is as follows. We have removed the animation-fill-mode from the shorthand as it doesn’t do anything in this case since our animation loops infinitely, has a non-zero duration and no delay:

/* new */
.jump { position: relative; transform: translateY(-100px); animation: jump $duration ease-in infinite; /* the rest */
} @keyframes jump { 20%, 75% { transform: translateY(0); animation-timing-function: ease-in-out; }

Note that we have different timing functions for the two animations, so we need to switch between them in the @keyframes. We still have the same effect, but we got rid of one element and one set of @keyframes.

Next, we do the same thing for the .rotate-in and .rotate-out elements and their @keyframes:

/* original */
.rotate-in { animation: rotate-in $duration ease-out infinite both; .rotate-out { animation: rotate-out $duration ease-in infinite both; }
} @keyframes rotate-in { 0% { transform: rotate(-135deg); } 20%, 100% { transform: rotate(0deg); }
} @keyframes rotate-out { 0%, 80% { transform: rotate(0); } 100% { transform: rotate(135deg); }

In a similar manner to the previous case, we add up the rotation values for each keyframe.

  • at 0%, we have -135deg from the first set of @keyframes and 0deg from the second, which gives us -135deg
  • at 20%, we have 0deg from the first set of @keyframes and 0deg from the second (as we have 0deg for any frame from 0% to 80%), which gives us 0deg
  • at 80%, we have 0deg from the first set of @keyframes (as we have 0deg for any frame from 20% to 100%) and 0deg from the second, which gives us 0deg
  • at 100%, we have 0deg from the first set of @keyframes and 135deg from the second, which gives us 135deg

This means we can compact things to:

/* new */
.rotate { transform: rotate(-135deg); animation: rotate $duration ease-out infinite;
} @keyframes rotate { 20%, 80% { transform: rotate(0deg); animation-timing-function: ease-in; } 100% { transform: rotate(135deg); }

We only have one element with a scaling transform that distorts our white square:

/* original */
.squeeze { transform-origin: 50% 100%; animation: squeeze $duration $easing infinite both;
} @keyframes squeeze { 0%, 4% { transform: scale(1); } 45% { transform: scale(1.8, 0.4); } 100% { transform: scale(1); }

There’s not really much we can do here in terms of compacting the code, save for removing the animation-fill-mode and grouping the 100% keyframe with the 0% and 4% ones:

/* new */
.squeeze { transform-origin: 50% 100%; animation: squeeze $duration $easing infinite;
} @keyframes squeeze { 0%, 4%, 100% { transform: scale(1); } 45% { transform: scale(1.8, .4); }

The innermost element (.square) is only used to display the white box and has no transform set on it.

 /* original */
.square { width: 100px; height: 100px; background: #fff;

This means we can get rid of it if we move its styles to its parent element.

/* new */
$d: 6.25em; .rotate { width: $d; height: $d; transform: rotate(-135deg); background: #fff; animation: rotate $duration ease-out infinite;

We got rid of three elements so far and our structure has become:

.frame .center .jump .squeeze .rotate .shadow

The outermost element (.frame) serves as a scene or container. This is the big blue square.

/* original */
.frame { position: absolute; top: 50%; left: 50%; width: 400px; height: 400px; margin-top: -200px; margin-left: -200px; border-radius: 2px; box-shadow: 1px 2px 10px 0px rgba(0,0,0,0.2); overflow: hidden; background: #3498db; color: #fff; font-family: 'Open Sans', Helvetica, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;

There’s no text in this demo, so we can get rid of the text-related properties. We can also get rid of the color property since, not only do we not have text anywhere in this demo, but we’re also not using this for any borders, shadows, backgrounds (via currentColor) and so on.

We can also avoid taking this containing element out of the document flow by using a flexbox layout on the body. This also eliminates the offsets and the margin properties.

/* new */
$s: 4*$d; body { display: flex; align-items: center; justify-content: center; height: 100vh;
} .frame { overflow: hidden; position: relative; width: $s; height: $s; border-radius: 2px; box-shadow: 1px 2px 10px rgba(#000, .2); background: #3498db;

We’ve also tied the dimensions of this element to those of the hopping square.

The .center element is only used for positioning its direct children (.jump and .shadow), so we can take it out altogether and use the offsets on it directly on these children.

We use absolute positioning on all .frame descendants. This makes the .jump and .squeeze elements 0x0 boxes, so we tweak the transform-origin for the squeezing transform (100% of 0 is always 0, but the value we want is half the square edge length .5*$d). We also set a margin of minus half the square edge length (-.5*$d) on the .rotate element (to compensate for the translate(-50%, -50%) we had on the removed .center element).

/* new */
.frame * { position: absolute, } .jump { top: $top; left: $left; /* same as before */
} .squeeze { transform-origin: 50% .5*$d; /* same as before */
} .rotate { margin: -.5*$d; /* same as before */

Finally, let’s take a look at the .shadow element.

/* original */
.shadow { position: absolute; z-index: -1; bottom: -2px; left: -4px; right: -4px; height: 2px; border-radius: 50%; background: rgba(0,0,0,0.2); box-shadow: 0 0 0px 8px rgba(0,0,0,0.2); animation: shadow $duration ease-in-out infinite both;
} @keyframes shadow { 0%, 100% { transform: scaleX(.5); } 45%, 50% { transform: scaleX(1.8); }

We’re of course removing the position since we’ve already set that for all descendants of the .frame. We can also get rid of the z-index if we move the .shadow before the .jump element in the DOM.

Next, we have the offsets. The midpoint of the shadow is offset by $left (just like the .jump element) horizontally and by $top plus half a square edge length (.5*$d) vertically.

We see a height that’s set to 2px. Along the other axis, the width computes to the square’s edge length ($d) plus 4px from the left and 4px from the right. That’s plus 8px in total. But one thing we notice is that the box-shadow with an 8px spread and no blur is just an extension of the background. So we can just increase the dimensions of the our element by twice the spread along both axes and get rid of the box-shadow altogether.

Just like in the case of the other elements, we also get rid of the animation-fill-mode from the animation shorthand:

/* new */
.shadow { margin: .5*($d - $sh-h) (-.5*$sh-w); width: $sh-w; height: $sh-h; border-radius: 50%; transform: scaleX(.5); background: rgba(#000, .2); animation: shadow $duration ease-in-out infinite;
} @keyframes shadow { 45%, 50% { transform: scaleX(1.8); }

We’ve now reduced the code in the original demo by about 40% while still getting the same result.

See the Pen by thebabydino (@thebabydino) on CodePen.

Our next step is to merge the .jump, .squeeze and rotate components into one, so that we go from three elements to a single one. Just as a reminder, the relevant styles we have at this point are:

.jump { transform: translateY(-100px); animation: jump $duration ease-in infinite;
} .squeeze { transform-origin: 50% .5*$d; animation: squeeze $duration $easing infinite;
} .rotate { transform: rotate(-135deg); animation: rotate $duration ease-out infinite;
} @keyframes jump { 20%, 75% { transform: translateY(0); animation-timing-function: ease-in-out; }
} @keyframes squeeze { 0%, 4%, 100% { transform: scale(1); } 45% { transform: scale(1.8, .4); }
} @keyframes rotate { 20%, 80% { transform: rotate(0deg); animation-timing-function: ease-in; } 100% { transform: rotate(135deg); }

The only problem here is that the scaling transform has a transform-origin that’s different from the default 50% 50%. Fortunately, we can go around that.

Any transform with a transform-origin different from the default is equivalent to a transform chain with default transform-origin that first translates the element such that its default transform-origin point (the 50% 50% point in the case of HTML elements and the 0 0 point of the viewBox in the case of SVG elements) goes to the desired transform-origin, applies the actual transformation we want (scaling, rotation, shearing, a combination of these… doesn’t matter) and then applies the reverse translation (the values for each of the axes of coordinates are multiplied by -1).

Any transform with a transform with a transform-origin different from the default is equivalent to a chain that translates the point of the default transform-origin to that of the custom one, performs the desired transform and then reverses the initial translation (live demo).

Putting this into code means that if we have any transform with transform-origin: $x1 $y1, the following two are equivalent:

/* transform on HTML element with transform-origin != default */ transform-origin: $x1 $y1;
transform: var(--transform); /* can be rotation, scaling, shearing */ /* equivalent transform chain on HTML element with default transform-origin */
transform: translate(calc(#{$x1} - 50%), calc(#{$y1} - 50%)) var(--transform) translate(calc(50% - #{$x1}), calc(50% - $y1);

In our particular case, we have the default transform-origin value along the x axis, so we only need to perform a translation along the y axis. By also replacing the hardcoded values with variables, we get the following transform chain:

transform: translateY(var(--y)) translateY(.5*$d) scale(var(--fx), var(--fy)) translateY(-.5*$d) rotate(var(--az));

We can compact this a bit by joining the first two translations:

transform: translateY(calc(var(--y) + #{.5*$d})) scale(var(--fx), var(--fy)) translateY(-.5*$d) rotate(var(--az));

We also put the three animations on the three elements into just one:

animation: jump $duration ease-in infinite, squeeze $duration $easing infinite, rotate $duration ease-out infinite;

And we modify the @keyframes so that we now animate the newly-introduced custom properties --y, --fx, --fy and --az:

@keyframes jump { 20%, 75% { --y: 0; animation-timing-function: ease-in-out; }
} @keyframes squeeze { 0%, 4%, 100% { --fx: 1; --fy: 1 } 45% { --fx: 1.8; --fy: .4 }
} @keyframes rotate { 20%, 80% { --az: 0deg; animation-timing-function: ease-in; } 100% { --az: 135deg }

However, this won’t work unless we register these CSS variables we have introduced and want to animate:

CSS.registerProperty({ 'name': '--y', 'syntax': '<length>', 'initialValue': '-100px'
}); CSS.registerProperty({ 'name': '--fx', 'syntax': '<number>', 'initialValue': 1
}); /* exactly the same for --fy */ CSS.registerProperty({ 'name': '--az', 'syntax': '<angle>', 'initialValue': '-135deg'

We now have a working demo of the method animating CSS variables. But given that our structure is now one wrapper with two children, we can reduce it further to one element and two pseudo-elements, thus getting the final version which can be seen below. It’s worth noting that this only works in Blink browsers with the Experimental Web Platform features flag enabled.

Animated gif. The square rotates in the air, falls down and gets squished against the ground, then bounces back up and the cycle repeats.
The final result (live, needs Houdini support)

The post What Houdini Means for Animating Transforms appeared first on CSS-Tricks.