One of the things that excites me most about the newest features of CSS, is the ability to replace a lot of the JS I’ve been using. While I’m not hating on Javascript (or jQuery, which is what I use), there’s no argument that script languages come with a lot of potential issues. There’s more overhead involved, more files to load and the potential for major failure and a broken site.
Over the past couple of months, I’ve been replacing a lot of Javascript functionality with CSS – making use of a bunch of new (or new-ish) CSS properties instead. I’ve made a few Codepens for you guys to check out some of the things you can do – and the best thing is, if a browser doesn’t support something (like vh in example 1), it’ll still render the item well enough for older browsers.
Example 1: 100% Viewport Height Areas
A lot of my clients love having the homepage hero be 100% height of the browser/viewport. This use to require calculating a user’s window height via JS, and recalculating when the window is resized on the fly. Instead, take a look at the new CSS units of vh and vw. Standing for viewport height and viewport width, these units allow you to set a container, independent of the parent to be a certain percentage of the viewport. So, 100vh means 100% of the viewport’s height, 62vw means 62% of the viewport’s width and so on.
Here’s a quick example:
See the Pen CSS vh unit example by Amber Weinberg (@amberweinberg) on CodePen.
Example 2: Animating Text on Load
Another favorite of designers, is to animate a page’s text on load, by having it slide up from the bottom of a div and fade in. This, too, no longer requires any scripting! We’ll simply add in a couple of animations and give it a bit of a delay to ensure the page is loaded before starting. BTW – I grabbed the amazing overshooting cubic-bezier curb from the amazing Val Head during her AEA Nashville talk.
See the Pen CSS Text Animations by Amber Weinberg (@amberweinberg) on CodePen.
Example 3: Animated Dropdown menus
I’ve always been a fan of doing dropdown menus in CSS. Usually dropdowns just require a
li:hover ul { display: block;} |
to make them work. However, if a client ever wanted something a bit fancier – an animated menu that accordions open and close, or fades in and out, I would switch to using jQuery. Now, I’ve been making all kinds of animated dropdown menus, modals and lightboxes with just CSS, by toggling transitions on properties like height and opacity.
See the Pen CSS Animated Dropdown Menu by Amber Weinberg (@amberweinberg) on CodePen.
Example 4: Vertical & Horizontal Positioning
The trick I use most now, using transforms allows us to vertically and horizontally align any element to it’s parent. This is so simple and requires only a few lines of CSS:
See the Pen Horizontal and Vertical Align Anything by Amber Weinberg (@amberweinberg) on CodePen.
Any others?
I would love to hear about some tricks you use to replace JS with CSS now. What am I missing?