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.

Design Microsites

Google, Airbnb, Slack, MailChimp, Facebook, Etsy, IBM, Dropbox… everybody has a design site these days.

Direct Link to Article — Permalink

The post Design Microsites appeared first on CSS-Tricks.

Extinct & Endangered

I’ve been watching a lot of nature documentaries lately. I like how you can either pay super close attention to them, or use them as background TV. I was a massive fan of the original Blue Planet, so it’s been cool watching the Blue Planet II episodes drop recently, as one example. A typical nature documentary will always have a little look how bad we’re screwing up the environment twist, which is the perfect time and place for such a message.

Speaking of perfect time and place, why not remind ourselves of all the endangered animals out there with placeholder images! That’s what Endangered Species Placeholders is. It’s like PlaceKitten, but for environmental good.

I also just came across this free icon set of extinct animals. 😢

Direct Link to Article — Permalink

The post Extinct & Endangered appeared first on CSS-Tricks.

Vox Accessibility Guidelines

I remember seeing these accessibility guidelines from Vox a while ago but it’s still interesting to go over them again today and see if there’s anything missing from my own process when it comes to improving accessibility.

And there’s an awful lot to remember! Color contrast, alt-text, keyboard navigation, focus states, and ARIA attributes are only a small snippet of the total number of things we ought to be mindful of when designing websites and so this checklist is certainly helpful for giving us all a good nudge from time to time.

Plus, it’s worth remembering that there are ways to advocate for improved accessibility in our projects.

Direct Link to Article — Permalink

The post Vox Accessibility Guidelines 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>
</figure>

This:

  • 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.

Kap

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.

LICEcap

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.

CloudApp

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.

Dragging

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>
</ul>

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.

Dropping

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 do you think about headless CMS?

(This is a sponsored post.)

Headless CMS is the new kid on the technology block. Some say it’s the only way forward, while others call it a fad without a future. So we decided to conduct a study to see what people think about headless CMS and why they want to use it. Has headless got a future?

Share with us your opinion on the headless CMS and get a chance to win $50 Amazon gift card.

Start the survey

Direct Link to Article — Permalink

The post ​What do you think about headless CMS? 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>
</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)));
Screenshot
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>
</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.

Productivity Tip: Time Tracking and Task Lists, Unite!

I’ve shared this little productivity tip with enough folks who have found it useful and figured I’d make a post out of it.

I love time tracking and I love task lists, but boy do I hate managing them both. So, I’ve been using my time tracker as my task list.

I use Harvest for time tracking. It allows you to create time entries in the future and I suspect many other time tracking apps do the same. That means today I can enter all the time entries I plan on doing tomorrow. Or, if I’m feeling super organized, I can create entries for the following week. All of my tasks are right there in front of me and ready to clock my time.

If I don’t get to a task that day? No worries. Harvest has a subtle feature that allows me to move a time entry from one day to another. Now, I’m good to go for the next day.

Again, other apps are probably capable of doing the same.

I know, it’s a super small thing but it delights me every day and helps me manage two important things in one.

The post Productivity Tip: Time Tracking and Task Lists, Unite! appeared first on CSS-Tricks.