0% found this document useful (0 votes)
43 views100 pages

2019-01-01 Web Designer UK

Uploaded by

Mihai GM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views100 pages

2019-01-01 Web Designer UK

Uploaded by

Mihai GM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

9000 9 1

EXPERT 40-PAGE GUIDE


Expert tutorials, techniques and inspiration

udini? Anim
t is Ho ate
Wha SVG
fr mea s urem
ding e
sibil
ity bo a r
ory
ces nt u
n it
St
ac
Grid &

ISSUE 282
EA
nsitions
M
ra

s
t

utout
SS

grid
C
O

-tem

y c
p

la
la
C

te-rows

Disp
E

ANIMATION TIPS
B

CSS Conic gradients


animation
6 0 fp s
int API
CSS Pa
NEED TO
ssor
or ce
prep

MASTER SASS
CSS Layou
OOCSS, ACSS, SMACSS or BEM?
t API
ms interview

YOU
y Willia
ssid

CSS
Ca

Tra
nsform
L L

s
A
les
Anima
tion API CSS Variab

am es

Co
f r
key

mbin
CS S

me e
tho
CSS Clip path
do log
ies
Meta
Welcome

Welcome
THE WEB DESIGNER MISSION
To be the most accessible and inspiring voice for the industry, offering cutting- Steven Jenkins
edge features and techniques vital to building future-proof online content Editor

CSS: style and substance Highlight

I
f you are reading this then there is a keyframes, performance and SVG animation along the
good chance you know what CSS is. We way. Want to know the ins and outs of CSS Grid? Then
like to call it the king of styling, but head to page 52 as we take you through the basics and
Cascading Style Sheets in 2018 have so beyond, and offer a few tips along the way.
much more to offer than simple styling. Not as sexy as animation but just as important is
This issue we decided it was time to optimisation. Head to page 58 to get quick and easy tips
show off some of the immense talents to lighten the code load and get faster-loading sites. CSS
that CSS has to offer and give an insight preprocessors let you extend CSS and make it even more
into some of the lesser-known but still essential powerful. We take a closer look at the very popular

“ The types of work


elements that anyone needing to sharpen up preprocessor Sass and show how to use it to style your
their skills really needs to know. sites. Everyone likes rules and best practices when it
So what is on offer? We kick off with eight comes to code, so on page 72 Ahmed Abuelgasim delves
we have put out are
pages all about CSS animation. This takes you into CSS methodologies and how to use them. Elsewhere, intentionally very
from storyboarding through to implementing a CodePen engineer Cassidy Williams shows off CSS art broad across verticals
simple project, while passing transitions, skills, and we look to the future with Houdini. Enjoy. and expressions. We
believe that broadness


Using a CSS methodology, or a combination of
many, can save you hours of development and debug
characterises us more
than any singular
piece of work

time, leading to more organised code

Web Designer finds out what’s going on at
Code and Theory. Page 32

Follow us on Twitter for all the news & conversation @WebDesignerMag


Visit our blog for opinion, freebies & more www.creativebloq.com

FREE – exclusive with this issue


Designerresources
44 Video Tuition – New chaptersofexpertPHPvideoguides

Assets
from Killersites(shop.killervideostore.com)
– 24LuminousPresets and10iPadPro(3G)mockups from
Sparklestock(sparklestock.com)
– Tutorial files andassets

www.filesilo.co.uk/webdesigner

welcome ________________________________________________ 3
Meta
Contributors

Future PLC Richmond House, 33 Richmond Hill,


Bournemouth, Dorset, BH2 6EZ

This issue’s panel of experts


Editorial
Editor Steven Jenkins
[email protected]
01202 586233
Art Editor Newton Ribeiro
Welcome to that bit of the mag where we learn more Editor in Chief Amy Hennessey

about the featured writers and contributors… Senior Art Editor Will Shum
Production Editor James Price
Contributors
Ahmed Abuelgasim, Mark Billen, Leon Brown, Matt Crouch,
Tam Hanna, Christian Heilmann, David Howell, Simon
Jones, Richard Mattka, Steven Roberts, Andy Salter, Mark
³ǝɖǔˢƺƫȒɎɎȒȅً!ƏɀɀǣƳɵáǣǼǼǣƏȅɀ

Photography
James Sheppard
All copyrights and trademarks are recognised and respected
Advertising
Media packs are available on request
Commercial Director Clare Dove
[email protected]
Steven Roberts Advertising Manager Mike Pyatt
[email protected]
Steven is a digital creative 01225 687538
Account Manager Chris Mitchell
from Stockton-on-Tees. He is [email protected]

currently leading UX, Design International


Web Designer is available for licensing.
and Frontend at Asemblr.com. Contact the International department
to discuss partnership opportunities
Steven has spoken at International Licensing Director Matt Ellis
conferences about CSS [email protected]
Subscriptions
animation this year, so for this Email enquiries [email protected]
issue we have gotten him to UK orderline & enquiries 0344 848 2852
Overseas order line and enquiries +44 (0) 344 848 2852
share some of his extensive Online orders & enquiries www.myfavouritemagazines.co.uk
Head of subscriptions Sharon Todd
knowledge with a host of tips
Circulation
and techniques. Head of Newstrade Tim Mathers
Page 42 Production
Head of Production Mark Constance
Production Project Manager Clare Scott
Advertising Production Manager Joanne Crosby

“animation,
Digital Editions Controller Jason Hudson

While it may seem a limited/lesser tool when it comes to Production Manager Nola Cokely
Management

CSS is actually really powerful and is capable of Brand Director Matthew Pierce
!ǝǣƺǔ!ȒȇɎƺȇɎ ǔˡƬƺȸ Aaron Asadi

producing beautifully smooth 60fps animations



Commercial Finance Director Dan Jotcham
Editorial Director Paul Newman
Head of Art & Design Greg Whittaker
Printed byáǣǼǼǣƏȅJǣƫƫȒȇɀً‫¨זא‬ǼƏȇƺɎƏȸɵ«ȒƏƳً
áǣǼǼƺȇǝƏǼǼًáà‫בًב׏‬æÁ
Distributed by xƏȸǸƺɎǔȒȸƬƺً‫!ד‬ǝɖȸƬǝǣǼǼ¨ǼƏƬƺً!ƏȇƏȸɵáǝƏȸǔً
Leon Brown Mark Shufflebottom Richard Mattka London, E14 5HU www.marketforce.co.uk Tel: 0203 787 9001
ISSN 1745-3534
Leon is a freelance web Mark is a professor of Richard is an award-winning
developer and trainer who Interaction Design at creative director, designer áƺƏȸƺƬȒȅȅǣɎɎƺƳɎȒȒȇǼɵɖɀǣȇǕȅƏǕƏɿǣȇƺȵƏȵƺȸɯǝǣƬǝǣɀƳƺȸǣɮƺƳǔȸȒȅ
assists web developers in Sheridan College near and developer, specialising ȸƺɀȵȒȇɀǣƫǼɵȅƏȇƏǕƺƳًƬƺȸɎǣˡƺƳǔȒȸƺɀɎȸɵƏȇƳƬǝǼȒȸǣȇƺ‫ٮ‬ǔȸƺƺȅƏȇɖǔƏƬɎɖȸƺِ
ÁǝƺȵƏȵƺȸǣȇɎǝǣɀȅƏǕƏɿǣȇƺɯƏɀɀȒɖȸƬƺƳƏȇƳȵȸȒƳɖƬƺƳǔȸȒȅɀɖɀɎƏǣȇƏƫǼƺ
creating efficient code for Toronto. In this issue he in VFX and entertainment managed forests, conforming to strict environmental and socioeconomic
projects. This issue he takes takes a peek at some of the projects. In this issue he standards. The manufacturing paper mill holds full FSC (Forest Stewardship
a look at CSS Grid and hottest properties out there, delves into the world of SVG !ȒɖȇƬǣǼ٣ƬƺȸɎǣˡƬƏɎǣȒȇƏȇƳƏƬƬȸƺƳǣɎƏɎǣȒȇ
shows how to create grids, who you should follow and and shows how to create All contents © 2018 Future Publishing Limited or published under licence. All
offering up some useful tips. great examples of and implement SVG for the ȸǣǕǝɎɀȸƺɀƺȸɮƺƳِzȒȵƏȸɎȒǔɎǝǣɀȅƏǕƏɿǣȇƺȅƏɵƫƺɖɀƺƳًɀɎȒȸƺƳًɎȸƏȇɀȅǣɎɎƺƳȒȸ
Page 52 cutting-edge CSS. Page 76 web. Page 80 reproduced in any way without the prior written permission of the publisher.
Future Publishing Limited (company number 2008885) is registered in
0ȇǕǼƏȇƳƏȇƳáƏǼƺɀِ«ƺǕǣɀɎƺȸƺƳȒǔˡƬƺ‫ي‬ªɖƏɵRȒɖɀƺًÁǝƺȅƫɖȸɵً ƏɎǝ ‫׏‬
1UA. All information contained in this publication is for information only and
is, as far as we are aware, correct at the time of going to press. Future cannot
accept any responsibility for errors or inaccuracies in such information. You
are advised to contact manufacturers and retailers directly with regard
Ahmed Abuelgasim Simon Jones Cassidy Williams to the price of products/services referred to in this publication. Apps and
ɯƺƫɀǣɎƺɀȅƺȇɎǣȒȇƺƳǣȇɎǝǣɀȵɖƫǼǣƬƏɎǣȒȇƏȸƺȇȒɎɖȇƳƺȸȒɖȸƬȒȇɎȸȒǼِáƺƏȸƺ
Ahmed is a self-taught Simon is a former corporate Cassidy is a senior software
not responsible for their contents or any other changes or updates to them.
front-end web developer engineering director, now engineer at CodePen. She’s ÁǝǣɀȅƏǕƏɿǣȇƺǣɀǔɖǼǼɵǣȇƳƺȵƺȇƳƺȇɎƏȇƳȇȒɎƏǔˡǼǣƏɎƺƳǣȇƏȇɵɯƏɵɯǣɎǝɎǝƺ
currently working for Potato. working at a tech startup. active in the developer companies mentioned herein.
In this issue he explains CSS He’s led full-stack teams community and one of If you submit material to us, you warrant that you own the material and/
methodologies, describes working with many different Glamour magazine’s 35 or have the necessary rights/permissions to supply the material and
the popular ones and technologies. This issue, he Women Under 35 Changing you automatically grant Future and its licensees a licence to publish
explains how to combine looks at how Sass can make the Tech Industry. This issue your submission in whole or in part in any/all issues and/or editions of
publications, in any format published worldwide and on associated websites,
them to create a custom it easier to manage we get insight into her world
social media channels and associated products. Any material you submit
one. Page 72 stylesheets. Page 64 and CSS art. Page 68 is sent at your own risk and, although every care is taken, neither Future
nor its employees, agents, subcontractors or licensees shall be liable for
ǼȒɀɀȒȸƳƏȅƏǕƺِáƺƏɀɀɖȅƺƏǼǼɖȇɀȒǼǣƬǣɎƺƳȅƏɎƺȸǣƏǼǣɀǔȒȸȵɖƫǼǣƬƏɎǣȒȇɖȇǼƺɀɀ
otherwise stated, and reserve the right to edit, amend, adapt all submissions.

Tam Hanna Matt Crouch


Tam believes in taking a
360-degree view of things.
Matt is a software engineer
at Vidsy, where they use
Follow us!
He believes achieving high Redux to power all of their Facebook: www.facebook.com/
performance in websites is React products. In this issue
always a team effort. In this Matt demonstrates how to WebDesignerUK
issue he demonstrates the get up to speed with the Twitter: twitter.com/ Future plc is a public Chief executive Zillah Byng-Thorne
techniques and tools concepts of Redux in the company quoted on the Chairman Richard Huntingford
needed to make your CSS first of a five-part React webdesignermag London Stock Exchange !ǝǣƺǔˡȇƏȇƬǣƏǼȒǔˡƬƺȸ Penny Ladkin-Brand
(symbol: FUTR)
blazingly fast. Page 58 series. Page 86 www.futureplc.com Tel +44 (0)1225 442 244

4 __________________________________________________experts
Meta

C ntents
Inside issue 282

Cutting-edge features, techniques and inspiration for web creatives


Chat with the team and other readers and discuss the latest tech, trends and techniques. Here’s how to stay in touch…
[email protected] s @WebDesignerMag swww.creativebloq.com

08 The state of JavaScript today


What’s popular? What are the big earners? Cover focus
Web Designer looks at the latest SOJ report

11 Keeping up with the web


industry
Web Designer catches up with Christian
Heilmann, who talks Twitter, Slack and more

12 WebKit: The best must-try


resources out there
Discover the libraries and frameworks you need

16 Lightbox
A showcase of inspirational sites and the
techniques used to create them

24 Back issues
Catch up on any issues of Web Designer that
you’ve missed by downloading a digital edition

26 Bon Voyage
Green Chameleon captain a site redesign for
superyacht experience-providers Asaro

32 Decoded Design
Web Designer talks to Code and Theory about
how they work and craft digital landscapes

40 All you need to be a CSS Pro


Discover essential CSS animation tips, how to
build with Grid, the best CSS methodologies,
how to optimise your code and much more

80 SVG on the web


SVG support is finally where it should be.
40
Discover how to use in your projects

92 Hosting listings
An extensive list of web hosting companies.
Pick the perfect host for your needs

94 Course listings
Want to start learning? Check out
what courses are out there with this list

98 Next month
What’s in the next issue of Web Designer 16 20

6 ________________________________________________ contents
TUTORIALS FILESILO
42 CSS animation tips & tricks 96 Get the latest must-have
-FBSO UIF ŢJOFS QPJOUT PG $44 BOJNBUJPO BOE resources and videos
how to implement them into a project s /FX DIBQUFST PG FYQFSU 1)1 WJEFP
guides from Killersites
52 Build with CSS Grid s  -VNJOPVT QSFTFUT BOE  J1BE 1SP
Discover the basics and beyond. Get essential mockups from Sparklestock
tips and techniques for better layouts
42
58 Get blazingly fast CSS
Cut out unnecessary code and slim down your
stylesheets for faster-loading sites

64 Style sites with Sass


Extend your CSS and make styling easier with
this popular preprocessor

68 CSS art with Cassidy Williams


Cassidy Williams, Senior Software Engineer at
CodePen, shows how to illustrate with CSS
68
72 CSS methodologies
Discover what methodologies are, which ones
are popular and create a custom one
Visit the Web Designer online shop at
76 Cutting-edge CSS myfavouritemagazines.co.uk
Stay on top of trends, find out what are the hot for the latest issue, back issues and specials
properties and what is Houdini

86 Manage React app data DIGITAL EDITION


-FBSO IPX UP DSFBUF BO "1*QPXFSFE TUBUF
Do you want to get your hands on a digital edition?
application and discover the benefits of a
Head to your preferred app store, download,
centralised data store 86 install and purchase the issue of choice
Google Play — bit.ly/2wetvGp
iTunes — apple.co/2igtBYq

Subscribe
today and
save
https://bit.ly/2sGwB3h
32

contents _________________________________________________ 7
News
CONTACT US AT: [email protected] | @WebDesignerMag

Header The tools, trends and news to


inspire your web projects
STAT
ATTACK
MOBILE
JavaScript: which are VENDORS
Who are the big
the popular choices?
The State of JavaScript 2018 survey gives a deep
players in the
European market?

insight into who’s using what in the world of JS Samsung

A 32.18%
longside HTML and CSS, these developers come from? The largest wanted to learn. Sitting in second place
JavaScript is the key contributor is the US with nearly 25 per was Vue.js, closely followed by Angular.
technology that is driving cent of respondents, with Australia and One interesting point was that over 46 per Down 3% on the same
forward web development. Germany offering over 5 per cent of cent wanted to learn to use Vue.js while time as last year
It is always moving forward, with new respondents. The UK contributed 3.78 per 33.8 per cent had used Angular but would
frameworks, tools and variations cent. Africa had the fewest respondents, not use it again. The remaining
seemingly making an appearance almost with Libya, Somalia, Angola and frameworks in the top six were Preact,
weekly. While new additions add more Mozambique only having one respondent Ember and Polymer, with around 25 per Apple
power and panache to a designer’s or each. As might be expected, the vast cent of respondents keen to learn Preact
%
developer’s arsenal, the hard part is
deciding which ones you need to be
paying attention to. Who are the big
majority – over 18,000 – of those who
participated in the survey were male.
There were 931 female respondents. A
and Polymer. But what other libraries got a
mention? The two standouts were Svelte
and Aurelia, with jQuery still hanging on in
28.81
Almost identical to the
players? Who are the newcomers to watch representation of how the market stands? there. Looking at back-end frameworks, previous year
out for? Who’s going to be the one that JS developers rarely use a single library Express is way out in front, with nearly 65
pays the big bucks? Choosing the right or framework. Even the popular choices per cent saying they had used it and would
path is not an easy task, so any help have a companion. For example, React again. Next was Next.js with nearly 9 per
newcomers and established developers users also connect with Redux, Express, cent. Looking at mobile and desktop it was Huawei
%
15.45
can get is always welcome. Mocha, Jasmine, Jest and of course ES6. close between Electron and React Native,
The State of JavaScript survey is an So what are the popular front-end with over 50 per cent keen to learn both.
annual report that provides a wealth of frameworks? As might be expected React The State of JavaScript survey is a
information on what developers are using, tops the charts, with 65 per cent using and goldmine of JS-related information, a On the rise, 4% up
on last year
what they’re happy with and what they happy to use it again. It’s not all roses fascinating read and beautifully presented.
want to learn. The latest report surveyed though, as 6.7 per cent had used it and We have only scratched the surface here
over 20,000 developers. So where do all would not use it again. But 19 per cent so look at 2018.stateofjs.com to see in full.

Xiaomi

creativebloq.com
3.78%
A low rise, 2% up
on last year
In-depth tutorials,
expert tips,
cutting-edge
features, industry
interviews, LG
inspiration and
%
opinion. Make
sure to get your
daily dose of e
3.72
Slight downward spiral,
by less than 1%
creativity, design
and development. today and save
40%
Source: http://gs.statcounter.com
(correct as of November 2018)

https://bit.ly/2qLxVl4

8 _____________________________________________________ news
HEAR FROM THE PROS
SIGN UP TO THE

NEWSLETTER TODAY!
DA RY
FRI T EVE
Y
OU

Get weekly news, tips & inspiration


SIGN UP NOW!
bit.ly/2KI5b7Y
Header
Inspiration

Sites of the month 02.

01.

03.

04. 01. Trade Aid


tradeaidchocolate.co.nz
A video background and overlaid graphics
combine to reinforce the site’s message

02. Old Spice – Big Lavender


biglavendergame.com
A classic old-school shooter is a smart way
to market Old Spice for a new generation

03. Human Forward


https://bit.ly/2A2PgJg
Big, bold and impressive animations make
sure that the user is constantly engaged

04. MiM event


gomim.com/en
Subtle background animations combine with
subtle movement as the users swipe or scroll

Graphics Colour picker Typesetter WordPress


Logotypes vol. 5 Sensei Fixture Miraculous
https://bit.ly/2DQkCHg https://bit.ly/2OTKjI5 https://bit.ly/2qZwpuk https://bit.ly/2TuCITS
A collection of gorgeous hand-drawn Based on 19th-century typefaces and Starting a Spotify style site? This theme offers
logotypes from designer Martin Schmetzer posters, Fixture offers four widths ranging what you need to create an online music store
#E01764
from Ultra Compressed to Expanded

#DE4477

#B57CA5

#A092AC

#8EABAF

10 ____________________________________________ Inspiration
Header
Comment

Keeping up with
the web industry
Web Designer recently caught up with Christian Heilmann at Reasons.to

A
lthough there is definitely value in social media, there is an issue with the
amount of noise it generates. On Twitter, the problem is exacerbated by the
fact that the timeline is not in sync any longer. It’s just a random presentation
of what might be interesting for you, which means you miss a lot. I’ve got
64,000 followers on Twitter, and yet I get all my resources via RSS feeds. I can’t
find much on Twitter because it gets lost in the noise.
The other problem that social media has caused is that instead of learning from each other,
people try to create resources that get the most likes or retweets. We try to shortcut a lot. The
priority is to make a cool headline that will get shared. I’ve blogged since 2005, and my blog posts
are always long. This used to work, but now people just zone out. We’ve become less patient with
learning. We’ve seen too many things come and go, and it feels like the investment in learning is
not worthwhile given the speed of changes in the market.
It’s not all bad, though. There’s a lot of good stuff happening on Slack groups. And, although it’s
not easy to use, I’d recommend trying Mastodon, which is like a more organised Twitter. There are
also a lot of learning resources on GitHub. There are training courses you can take on other
platforms, but GitHub is where people are channelling a lot of their efforts now. It also tends to get
the most edits, so content there is generally up-to-date.
If you want to get started, taking part in open source projects is the best way. Helping with a
typo or a bit of documentation, or making a demo for a product and asking the owner if they want
to have it on the GitHub repo is a great way to get your name known. People publish great things
as open source but often don’t have time to show the implementations or write documentation.
Although these platforms provide a good place for people to get involved in the industry, we
need to work on being more welcoming to newcomers. The web industry is not accepting of
people who don’t speak the right language. People and tutorials hide behind massive terms and
clever-sounding messages. This could be a natural thing. When you’re an expert and you want to
talk to other experts, sooner or later you develop a defined lingo, and that’s fine. But starting with
this lingo and overwhelming newcomers that want to learn something is annoying. People are
repeating the same sentences that they don’t even understand, just trying to fit in with the crowd.
Christian Heilmann Because of this peer pressure, newcomers often don’t dare to speak up when they don’t
christianheilmann.com understand. I love that, as somebody who is in the know, I can do that for them. I interfere and say,
Twitter: @codepo8 “OK, but what does that mean?” I’m happy to pretend (or sometimes be honest) that I don’t know
things, just to be an example for other people so they might find the courage to do the same.
This is a particular problem with new technologies and buzz phrases. People make a lot of
money by saying half-clever things about a technology rather than showing what it can be used
for. Everything is Blockchain right now. 90 per cent of people on the planet can’t explain what

I’m happy to Blockchain is. “We’re using Blockchain for that” – of course. The same way we used ‘the cloud’.
Being on the bleeding edge is interesting, but we’re chasing our own tails a bit and not giving

pretend (or new technologies enough time to mature and become useful. I want to see more products being
created with these technologies. I’m currently working on a W3C proposal for Machine Learning

sometimes be in the browser. It would mean you could do facial recognition, audio recognition and similar ‘AI’
tasks on your own machine, rather than having to send it to Amazon, Google or Microsoft to get it
honest) that I don’t analysed there. That way the privacy of your own data is much more given. There’s an open
standard for the file format but not an open standard for the access to it. That’s something we’re
know things, just to proposing right now, and that’s what I want to see much more of.

be an example for
Everybody sells their current solutions as magic rather than explaining them. I know graffiti
painters who learned how to paint on canvas first because they need to know the craft before

other people they can do the art. They are stunning at what they do as they chose to subvert the original art.
We’re not patient enough right now to learn the ropes before calling ourselves experts.

Comment______________________________________________ 11
webkit Discover the must-try resources that
will make your site a better place

SVG Filters
yoksel.github.io/svg-filters/#
Want to see SVG filters in action without
applying lines and lines of code? Then this
rather neat online tool enables you to add
GaussianBlur to see the filter in action. Like
it? Copy the code and use in your project.
Experiment with the other filters to get the
different filters with a single click. Add look you want.

TOP 5
CODEPENS
Be inspired by this collection of smart
and interesting codebases

Relaxing Recursive React Old-school DVD


codepen.io/terabaud/pen/RqQmOX codepen.io/foleyatwork/pen/MzGKWq
An animated repeating pattern built with If you have a DVD player, this a faithful
React that mesmerises and relaxes. Watch in recreation of the sleep screen. If not, watch
a darkened room and feel the calm. and admire what you’re missing.

12 _____________________________________________ resources
Header
Resources
CONTACT US AT: [email protected] | @WebDesignerMag

CSS file icons Day.js


colorswall.github.io/CSS-file-icons github.com/iamkun/dayjs
Pure CSS file icons for popular extensions, including doc, This is a minimalist JavaScript library that parses, validates,
docx, log, txt, wps, csv, dat, ppt, xml, mp3, wav, avi, mov, mp4. manipulates and displays dates and times for today’s
Available in different sizes. browsers with a largely Moment.js-compatible API

Video Crop Smoothie Charts


video-crop.com smoothiecharts.org
Want to crop your videos quickly and easily? This drag and Turn your data into live streaming graphs with this JavaScript
drop tool is the answer and comes as part of a collection of Charting library. Read the Ten Minute Tutorial and create
video tools with the easy-to-use Chart Builder.

Catch the Carrot Periodic Table Rounded Range Slider


codepen.io/MalaikaMI/pen/VVQpmW codepen.io/oliviale/pen/ZmvPPd codepen.io/Artemis1/pen/Gwywoj
A simple game where you have to catch the A CSS based – slightly modified – periodic A styled-up temperature gauge that shows
carrot. Give it a try and see if you can beat table that cleverly reflects how Olivia, the Fahrenheit and centigrade. Use the slider to
our score of five. designer, wastes their time on the internet. change or enter manually.

resources ______________________________________________13
webkit Discover the must-try resources that
will make your site a better place

sitespeed.io
sitespeed.io
Sitespeed.io is a set of open source tools you
might or might not have heard of that make it
easy to monitor and measure the
helpful instructions on how to install and
which tools to use for what. Only interested
in timing metrics, then use Browsertime.
performance of your website. Includes Want to find issues, use The Coach.

TOP 5
WORDPRESS
THEMES
Need a new page design fast? Then
check out this collection of themes

Buzz Stone Jawn


https://bit.ly/2OYnlzv mvpthemes.com/jawn
A modern, contemporary image-led news/ Big image, smart styles and modern fonts
magazine style theme. Homepage options make this theme the ideal option for the
enable you to get a more custom option. modern-day blogger.

14 _____________________________________________ resources
Header
Resources
CONTACT US AT: [email protected] | @WebDesignerMag

SoundJS Colorblindly
createjs.com/soundjs https://bit.ly/2DJKa8o
A JavaScript library that helps make working with Accessibility is important, and this Chrome extension
audio “a breeze”. It offers a simple API that abstracts simulates what users with colourblindness will see in
HTML5 sound implementation. the web browser. It offers eight different settings.

Lookback Vyoo
lookback.io veed.io/vyoo
Want to know how people are using your site or app? This is simple. It offers beautiful, free vertical videos,
Of course you do. Do real-time video testing, remote with new ones uploaded every week. Download the
testing and in-person testing. video or edit with Veed.

Insider Flagrant Hayden


darinka.design/insider https://bit.ly/2AjELkP https://bit.ly/2DIPjxp
A classic, clean image-led layout with image A modern image-led gallery theme. Ideal for An e-commerce theme aimed at children. As
animations to help engage users. A photographers, artists, illustrators or any you might expect, it offers bright, bold
multipurpose theme with a touch of style. other image-led site. colours and easy-to-navigate menus.

resources ______________________________________________15
Land Life Company landlifecompany.com

16 ________________________________________________ lightbox
LightBox

Designer:
Qikker Online www.qikkeronline.nl
Based in
Amsterdam
and
operating
across 25
countries,
Land Life
Company’s
mission is to
help reforest
2 billion
hectares of
degraded
land

Colours

#888208 #726959

#D79C62 #DAA90E

Tools
WordPress, PHP, Yahoo UI
(JavaScript), YouTube

Fonts

Avenir by Adrian Frutiger,


plus Montserrat by Julieta
Ulanovsky are both used to
render page headings and
paragraphs throughout.

Spectral font by Production


Type, also available via
Google Fonts, provides the
serif styled typeface found
on links and quotes.

lightbox_________________________________________________17
Above
Project locations are plotted on a
rollover world map, with key area
hotspots highlighted for viewing
details on click
Far left
Projects can also be viewed in a
more linear layout, stacking a
stream of photos and quotes under
links for quick navigation
Left
Beyond the opening header, a
minimal colour palette is employed
to allow beautiful location
photography to be more impactful

18 ________________________________________________ lightbox
LightBox
g
Land Life Company

Create a cursor-controlled
interactive spotlight effect
A spotlight effect allows users to search and reveal additional parts of background imagery

1. HTML document initiation firstChild); content: "";


The first step is to define the webpage as a HTML display: block;
document. This consists of the HTML document *** STEP 4 HERE width: 100%;
container used to contain the head and body sections. }); height: 100%;
While the head section is used to incorporate the background-image: linear-gradient(to
external CSS and JavaScript resources, the body section 4. Movement listener right,
is used to store the content elements that are created in JavaScript is also used to attach an event listener to the rgba(0,0,0,0) 0%,
the next step. header element found in step 3. This listener executes rgba(0,0,0,0) 30%,
<!DOCTYPE html> code to find the child element created in step 3, upon rgba(0,0,0,1) 50%,
<html> which new styles are calculated for its placement and rgba(0,0,0,1)
<head> background positions. Mouse co-ordinates relative to the );
<title>Cursor Spotlight</title> header element are provided via the 'e' parameter. top: 0;
<link rel="stylesheet" type="text/css" header.addEventListener("mousemove", left: 0;
href="styles.css" /> function(e){ }
<script src="code.js"></script> var shape = this.firstChild;
</head> var x = e.offsetX; 7. Header children
<body> var y = e.offsetY; All first-level children of the header element require
*** STEP 2 HERE shape.style.left = x + "px"; absolute positioning in order to benefit from having a
</body> shape.style.top = y + "px"; z-index. The first child is also styled with a width and
</html> height, along with a full border radius to appear as a
shape.style.backgroundPosition = (0-x)+"px circle. The same background used for the header is also
2. Body content "+(0-y)+"px"; applied – enabling this to be modified by the JavaScript in
The content placed inside the document body sets up a }); response to any mouse movement.
header element used to store content required for the header > *{
effect. The div element is used as a container to control 5. CSS: header styling position: absolute;
text and image content we want to place inside the Create a new file called 'styles.css'. This step defines the }
header element. This HTML is defined to be SEO friendly styling for the header element, making it cover half of the header > *:first-child{
by keeping elements and styling for the effect defined web page. The background image for the element is also display: block;
separately in the CSS and JavaScript files. selected, with its size adapted to cover the full width of width: 40vh;
<header> the header element. Overflow and cursor presentation height: 40vh;
<div> are set to hidden to keep the effect tidy. background: red;
<h1>Hello</h1> header{ border-radius: 100%;
</div> position: relative; background: url(image.jpg);
</header> display: block; background-size: 100vw;
height: 50vh; }
3. JavaScript load event background: url(image.jpg);
Create a new file called 'code.js'. For the effect to work, background-size: 100%;
JavaScript is used to modify the header element created cursor: none;
in the previous step. This header element is only available overflow: hidden;
after the page has loaded. An event listener is applied to color: #fff;
the window to execute a function containing specific }
instructions after the page has loaded. This step finds
the header section and inserts a span element as the 6. Gradient overlay
first child. A gradient is required to be placed over the background
window.addEventListener("load",function(){ image. The 'before' virtual element is used to achieve this
var header = document. in a way that avoids additional HTML requirements. This
querySelector("header"); element is sized and positioned to cover the full space of
var node = document. the header element with its own background image,
createElement("span"); created with a CSS-generated linear gradient.
var handle header::before{
header.insertBefore(node, header. position: absolute;

lightbox________________________________________________ 19
The Adventure of
Detective Moustachio zbeul.studio

20 _______________________________________________ lightbox
LightBox
Designers:
Renaud Rohlinger, Developer Sofiane Hocine, Art Lucas Fiorella, Music
renaudrohlinger.com

More
interactive
experience
than website,
Detective
Moustachio is
a pixelated,
side-scrolling
platform
game
optimised for
desktop and
mobile

Colours

#E67F46 #571874

#1DB5FD #FD0481

Tools
GSAP, core-js, Babel,
Amazon AWS

Fonts

FFF Forward font by Fonts


For Flash is the decidedly
blocky typeface used for all
the retro videogame text.

Montserrat font by Julieta


Ulanovsky is available via
Google Fonts, and is also
referenced within the CSS
in 400 and 500 weights.

lightbox_________________________________________________21
Top
A skippable 'cut scene' intro
presents what this HTML5 version
of the game has in store for
Detective Moustachio
Left
Essentially an auto-run platform
game, player controls are kept
simple on all devices, despite some
clever upside-down physics at times
Above
The select level menu tracks
progress, showing special coins
collected and also enabling players
to plot their own path

22________________________________________________ lightbox
LightBox
g
The Adventure of Detective Moustachio

Create a blip effect for


hovered content
Use a visual blip effect to indicate interactive content elements

1. Initiate the document enables any child elements to be placed in relation to display: block;
The first step is to define the HTML document – i.e. the their position, along with height and width properties position: absolute;
webpage. This consists of the HTML document container, becoming available. These are all required for the top: 0;
which stores the head and body sections. The head animation defined in step 7. left: 0;
section is used to load the external CSS file, and the body .blipbox{ background: rgba(0,0,0,.5);
is used to store the webpage content created in step 2. display: inline-block; width: 100%;
<!DOCTYPE html> position: relative; height: 100%;
<html> } opacity: 0;
<head> }
<title>Blip Animation</title> 5. Blip hover
<link rel="stylesheet" type="text/css" A style rule is required to trigger an animation to 7. Blip animation
href="styles.css" /> elements using the 'blipbox' class whenever they are The animation is required to move the 'after' element
</head> hovered over by the mouse cursor. This animation is from the top left corner to slightly behind the top left
<body> applied to a virtual 'after' element, hence the use of the corner while increasing its size. This provides the effect of
*** STEP 2 HERE 'hover' and 'after' CSS selectors. The animation attribute the element increasing its size over the element. Another
</body> specifies the name of the @keyframes animation and the part of the blip effect is how the animation changes the
</html> duration to play it. . opacity from fully visible to invisible.
.blipbox:hover::after{ @keyframes blipAnim{
2. Page content animation: blipAnim .7s; from{
The page content consists of an article and two } top: 0;
containers. The effect can be applied to any element left: 0;
using the 'blipbox' class. Images act in a way that stops 6. Overlay styling opacity: 1;
the blip effect, and this example wraps each image inside The default settings of the 'blipbox' overlay are created }
a span element so the blip effect can work with images. using the CSS 'after' virtual element – as also referenced to{
<article class="blipbox"> in step 5. This element is required to have default settings opacity: 0;
<h1>Hello</h1> to define the starting state of the animation. It will cover top: -10%;
</article> the full area of the element, with semi-transparent black left: -10%;
<span class="blipbox"><img src="img/photo1. background. Opacity is set to zero in order to hide the width: 120%;
jpg" /></span> element until the animation is triggered from step 5. height: 120%;
<span class="blipbox"><img src="img/photo2. .blipbox::after{ }
jpg" /></span> content: ""; }

3. CSS: article
The example article is set to cover half of the vertical
display space, with margin settings set to guarantee it to
be centrally positioned. The styling for this element is
separate and independent from the blip effect, although
it is required to show how the effect would work with a
content container element.
article{
display: block !important;
margin: 2em auto 2em auto;
border: 1mm solid #000;
padding: 1em;
width: 50%;
clear: both;
}

4. Blipbox definition
Elements using the 'blipbox' class are required to display
as inline-block elements using relative positioning. This

lightbox________________________________________________ 23
NEVER MISS AN ISSUE!

Issue 280
30 best HTML, CSS and JS APIs and
elements, research your keywords,
interactive JS charts and What is the
Web of Things?

SAVE UP
Issue 281 TO 43% Issue 275
Design, develop and create with
top Google tools, add glitch WITH A DIGITAL 50 must-try tools for designers and

SUBSCRIPTION
developers, how to add awesome
effects with CSS, animate with audio, Progressive Web Apps and

GSAP and code UX patterns SEE PAGE 50 interactive images

GOT AN APPLE DEVICE?


Download Web Designer’s digital edition for your iPad, iPhone or iPod touch

https://apple.co/1hsGYgl
CATCH UP ON ANY ISSUES YOU’VE MISSED BY DOWNLOADING
OUR DIGITAL EDITIONS https://bit.ly/2rh73Xk

Issue 279
Pro tips to build animation for the
Issue 278
What’s new in JavaScript, say hello
Issue 277
Hot new CSS properties for today,
Issue 276
Build your own augmented reality
web, 23 ways to make your app to Google Flutter, build with CSS build interactive 3D, streamline your app, get started with Three.js,
shine, work with variable fonts and Grid, work with WebRTC and create design workflow with Sketch and power up with Sass and Stylus and
what’s new in Node 10 patterns with CSS code a real-time React app generate web components

Issue 274
The new rules and top tools for UX,
Issue 273
SEO Today, 20 hot new libraries and
Issue 272
Build with Web Components,
Issue 271
28-page design special. Create the
5 hot new CSS properties, use the frameworks, ten pages of ReactJS 8 WordPress security secrets, perfect colour palette, top type
CSS Paint API, add particle effects tutorials, get started with Rust and Web Accessibility, convert visitors to trends, design and build grid layouts
and discover JSX build a WebGL racing game customers and data visualisations and automate your workflow

PREFER TO READ ON ANDROID, PC OR MAC?


Web Designer magazine is also available on Google Play and Zinio

https://tinyurl.com/yalm3wul https://bit.ly/2xPbv4p
26__________________________________________design diary
SUPERYACHT EXPERIENCE-PROVIDERS ASARO CHOSE GREEN CHAMELEON TO
CAPTAIN A WEBSITE REDESIGN THAT WOULDN’T LEAVE GUESTS ALL AT SEA

f you mused on the virtues of professional web design today, a big attraction must
ASARO be variety. Because the internet and digital is now so vital and so ubiquitous in
asaro.co.uk marketing, businesses and organisations of all conceivable kinds require quality
websites. Take, for instance, a company that creates luxury immersive experiences
by
on superyachts and megayachts – Asaro. This company designs and delivers

Green Chameleon bespoke, immersive theatrical experiences on an unimaginable scale all around the world.
So when a client like that seeks out an online revamp, whoever answers the SOS call is in
craftedby c.com for a pretty diverse ride.
In this instance, the agency it reached out to is well-known within Web Designer pages
Project duration for adapting to any project environment. Bristol-based Green Chameleon is a creative
4 months production studio that specialises in crafting extraordinary brand experiences that stand
out, not blend in. Founded in 2012, this agency comprises a growing ‘crew’ of 13 talented
designers, animators, developers, videographers and account managers. “We were
People involved approached by Asaro to redesign their website and help them better reflect their position
within the seven-star luxury world,” recalls GC’s Design Director Nathan Riley. “They
Nathan Riley needed a creative way to visually represent their exclusive service offering, as
Design Director
photography was scarce due to the private nature of their events.”
Asaro’s audiences would be the captains, crew and owners of these immense vessels, as
Tom Anderson well as the guests who commission and enjoy the events they organise. So in order to
Creative Director speak their language while being discreet, the designers employed custom CGI renders,
created to represent the client’s event genres. “Inspired by water drop photography, we set
Dan Linthwaite out to create a striking and memorable aesthetic that embodied the spirit of each event
Art Director and encapsulates the mystery and adventure weaved into all of Asaro’s offerings.”

Jack Harvatt
Designer

Jake Whiteley
Senior Back-end Developer

Jesper Landberg
Front-end Developer (Twotwentytwo)

Nathan Riley Tom Anderson Dan Linthwaite


Design Director Creative Director Art Director

design diary _________________________________________ 27


BON VOYAGE

NAUTICALLY NICE with page layouts across print and digital.


Green Chameleon knew that this kind of While offering the client insight into GC’s vision
imagery would also tie the theatrical nature of and thought process, this phase also helped to
the events to the nautical theme of yachting, hone creative direction in the early stages of
which underpins everything Asaro does. As a the project and added context to the initial
perceptive agency, GC immediately recognised design presentation. “The biggest challenge we
the potential for the project and the faced here was working out how to best
opportunity to work with a unique client in visualise the Asaro offering,” Anderson admits.
such a unique sector. “To say we were excited “They operate in such a private and exclusive
would be an understatement!” enthuses sector, and as a result photography and
Creative Director Tom Anderson. “The brief and documentation of the actual experiences was
scope of work would draw on a huge breadth very limited. It was this challenge that led us to
of our skills, allowing us to really utilise our create a series of computer-generated images
team’s creative and technical talents to deliver to allude to the immensely detailed and
a stunning outcome, which is precisely the type immersive experiences that Asaro offers.”
of project we love to work The art direction would
on.” They actually took draw on a blend of water
the initial project call not drop photography and
in sunny Bristol but in theatrical poster design,
Barcelona while attending with the aesthetic of this
the OFFF design photographic style
conference. Already seeming to fit nicely with
feeling inspired by the the project’s obvious
show, learning about the nautical theme.
possibility of working on
such an interesting and EXTRA HANDS
fun project got the gang Fresh from a conception
particularly excited. phase that involved the
“After meeting with the Asaro founders and majority of the team, it was time to start facing
the wider team we felt the chemistry was there the practicalities of building. Two members of the
to make something extraordinary, and after GC design team were assigned to handle the
submitting a proposal for the work we were majority of the design work on the website
thrilled to find out we’d been chosen to take the moving forwards. The focus for creating the
project on and realise our visions.” stunning 3D assets would fall on Art Director Dan
Linthwaite, while Design Director Nathan
PLOTTING COURSE handled the site and interaction design. In
Making proper contact on their return home addition, they actually drafted in a helpful
would be pivotal to touching base and talking. Swedish agency friend in the form of
As an agency, Green Chameleon isn’t exclusive Twotwentytwo’s Jesper Landberg. “We worked
in recognising that communication is key to extremely closely with Front-end Developer
any successful working relationship from the Jesper to come up with the best interactions,
off. This catalyst for the delivery of great work keeping performance in mind throughout,”
across any given project has resulted in Green confirms Nathan. “Sometimes this involved
Chameleon structuring its design process providing animated demos or specific micro-
around those principles. interactions but more often just chatting through
“We make sure that from the beginning of ideas and seeing how best to achieve them.”
every project, the client is appointed a member This kind of extra technical assistance was
of our Client Services team to liaise with appreciated, seeing as the WebGL underwater
throughout, as well as being given exposure to effect applied to the 3D renders would take
all members of the creative team,” says Nathan. considerable research and development to get
“This ensures that creative requirements are right. “The code uses a displacement map to alter
understood and clearly interpreted our end the intensity of the effect, so with this in mind we
and that any specific questions are answered created several variations of the map to get the
directly and efficiently. We take an integrated effect just right. In the CMS we built the ability to
approach to design and development, and the swap out the masks, meaning it was really
client is involved regularly to feedback over the efficient to try out a new version of the effect,
course of the project.” cutting out a lot of needless back and forth
With progress made on plotting the overall during the testing phase.”
course, the focus could move onto discussing Built upon a custom WordPress framework,
concepts. Presenting visual mood boards to the website would eventually be hosted on an
convey initial ideas for the look and feel, the Nginx/Apache hybrid DigitalOcean droplet
team explored colours and typography, along running Ubuntu 18.04 LTS and PHP 7.2. As a rule

28__________________________________________design diary
BON VOYAGE

Asaro’s website draws on


the nautical theme while
alluding to the mystery
and adventure on offer

“We were driven by the ambition


to create a striking visual that not
only told a story but conveyed
the idea of a mood without giving
too much away,” describes
Creative Director Tom Anderson
when quizzed on the initial
design motivation. “It was here
that we drew inspiration from
theatrical poster design and
chose CGI over photography,
because we felt it gave us more
freedom creatively, as well as
ensuring consistency moving
forwards.” This inspiration would
largely inform the project’s art
direction by mixing in a big
dollop of water drop
photography for good measure.
Underlining the nautical
themes associated with a luxury
superyacht experience, these
metaphors applied to the 3D
rendering, and WebGL work
would also feed into other areas.
“The website navigation and
layout of the site was inspired by
the journeys and maps that are at
the heart of an Asaro experience.
The site features an interactive
dotted line that fills up as the
user scrolls down the page,
taking them on a journey of the
Asaro offering. We also built an
interactive slider to unlock the
experiences section that evokes
a sense of discovery and
playfulness, a nod back to the
Asaro experiences themselves.”

design diary _________________________________________29


BON VOYAGE

It stands to reason that all


agencies like to be loved
and place massive
emphasis on satisfying
their clients. The Green
Chameleon crew are no
exception of course, and a
big part of the excitement
of embarking on a project
journey such as this is in
seeing how the site fulfils
the brief postlaunch. “The
website has generated
positive feedback from
Asaro’s industry peers and
their clientele,” beams GC
Creative Director Tom
Anderson. “The brochure
was also well received at
the Monaco Yacht Show,
proving that the overall
redesign worked to
highlight Asaro’s standing
as a luxury brand with a
modern approach among a
field saturated in the usual
hallmarks of opulence.”
This was hugely important
to the client’s overall
campaign objective, with
Asaro’s rebranding drive
being christened at such a
Champagne-soaked
industry event.
The site’s production
deadline was timed to have
the website launched and
live in order to premiere at
the show, but perhaps the
bigger reception has been
how the online world has
embraced the work. “We
were extremely proud that
the website won numerous
notable design awards,
including Site of the Day
awards from Awwwards,
FWA and CSS Design
Awards and features on
Communication Arts and
Mindsparkle Mag, as well
as a Mobile Excellence &
Developer Award from
Awwwards, and not to
mention the very exciting
FWAWWWARD.”

30 _________________________________________design diary
BON VOYAGE

We asked Green Chameleon’s


Design Director Nathan Riley to
identify a favourite feature
from the project

“The standout feature for us has to


be the custom CGI renders that
were created to represent Asaro’s
event genres. The striking visuals
have proven to be a powerful
visual mechanic that has created
intrigue among Asaro’s
prospective clients. These assets
have been a great success, but
they were also a lot of fun to create
and we were able to try out some
new techniques in the process.”

of thumb, the GC developers used plugins and two parties. The finishing line would arrive in the
third-party code as little as possible, preferring to form of the Monaco Yacht Show, an exclusive
build purpose-driven solutions in-house. event for superyacht owners, charterers and
decision-makers in the yachting and luxury
JQUERY MAROONED industries. The client, Asaro, was naturally
“With Asaro being so JavaScript heavy, this led attending the show, with a view to launch their
us to completely drop jQuery for the project, exciting new rebrand.
which threw a lot of traditional WordPress form “The main challenge was ensuring that
solutions out the window,” begins Senior everything, from the business cards to the
Back-end Developer Jake Whiteley. “We used printed brochure, and most importantly the
the popular Axios library to handle the form website, were all finalised and perfectly polished
submission, along with our custom framework in time for the show,” says Tom Anderson. “Plus,
to implement Laravel-like request validation on remember that the emphasis on the website’s
the backend.” This decision to throw jQuery speed and performance was even greater in the
overboard would actually prove to be very instance of this project because we were
popular with the developers, becoming a tactic constrained by the 3G or 4G connections at sea.
they intend to actively pursue on future projects. With the majority of the target audience being
Keen to be as agile as possible, the GC coders captains of superyachts, we had to ensure the
also tried to keep back and front-end site’s load speeds were fast and optimised for
development happening in parallel. “Working in mobile and tablet viewing, as well as desktop.”
parallel enables us to respond to site structure Similarly, it was never going to be a case of
and content changes as quickly as possible, and just pushing the finished site out into the ocean
works well with our interaction design process. of the world wide web. As part of such a
Plus the transference of ideas from our shipshape relationship, there was a commitment
designers’ heads into working animations can to keep the thing afloat after setting sail. “Along
involve a lot of fine-tuning, and parallel with managing the hosting of the Asaro website,
development ensures that progress is being we’re also on hand for any additions or
made, regardless of any blockers. With Asaro maintenance that our designers or developers
having such a tight turnaround time, this meant are required to provide support with,” Nathan
front-loading the back-end efforts to ensure that concludes. “The site was built on WordPress and
the site content structure was in place before so the majority of content is editable, which
the main bulk of work started.” purposefully gives the client full control for
future developments. However, we encourage
FIT FOR LAUNCH an ongoing relationship with all our clients and
Such a strategy was of course pivotal given the have already begun discussing with the Asaro
tight four-month deadline agreed between the people about what’s on the horizon next!”

design diary __________________________________________31


D e co d e d D e s ig n

WHO
Code and Theory

WHAT
interactive products,
campaigns, advertising,
branded experiences,
design, branding, user
experience, interface
design, graphic design,
strategy, engineering,
product UI, website
design and development,
motion graphics, rich
media, and social media

WHERE
1 World Trade Center,
62nd Floor, New York,
NY 10007

WEB
www.codeandtheory.com

KEY CLIENTS
[1] adidas

[2] Comcast

[3] NBC

[4] Nasdaq

[5] American Bar


Association

Mike Treff (President)


explaining his latest concept
to an enthralled audience

32 ___________________________________________________profile
DESIGN
With extensive experience in crafting digital landscapes, Code
and Theory defines the relationship brands have with their
customers across multiple channels. Connecting design and
technology, Code and Theory creates user experiences that
reinvent how companies can digitally transform
The Code and
Theory team
admiring the
inspirational view
from their New
York offices

an Gardner, the CEO of Code and additional offices in San Francisco, London

D Theory, co-founded the agency in 2001


with his childhood friend Brandon
Ralph. Dan and Brandon were working in the
and Manila.
Code and Theory craft new digital
experiences. This level of understanding is
digital department of Draft, where they quickly reflected in the name Dan and Brandon chose
realised that the full potential of digital did not for their agency, as Dan explains: “The name
exist in CD-ROMs, and so they left to form their came first from a desire to play in the area
own agency. where creativity and technology intersect. We
As a recent graduate of the University of wanted to imply our digital focus without being
Buffalo, Dan had received a BFA in Computer exceedingly overt and having a ‘.com’ in the
Art, while Brandon had dropped out of NYU to middle of our name. Code and Theory was a
work full time. Realising that their ideas were novel idea in 2001, so it wasn’t hard to get the
not being put into practice, they decided to domain. Our name really speaks to why the
start their agency to create transformative agency was formed and our approach to
digital experiences and products. creativity, through strategy and technology.”
Initially working out of a one-bedroom The website that Code and Theory currently
apartment on the Lower East Side in New York maintains speaks volumes about not only the
City, they then moved into a Wi-Fi-less, approach the agency takes to digital design,
abandoned floor of a downtown office building. but also its skills with today’s digital tools.
Today, they are headquartered on the 62nd Michael Treff (President) explains the
floor of the World Trade Center and have importance of maintaining a powerful and

profile___________________________________________________ 33
D e co d e d D e s ig n

Keisha Brescia (COO, PMX Agency), Larry Muller (Chief Operating Officer),
Naomi Soviecke (Financial Operations Manager), Naren Persaud (Financial
Controller), Jonathan Chan (PMX) (Controller) and two other colleagues
from PMX thrash out a new proposal

informative site: “It’s what guides the first work just for the sake of new business. That
impression when someone is looking into us, so being said, we’ve been extremely fortunate to
we think it’s very important. Not only is the work with clients who trust us with work that
website a window into our agency, employees, has allowed us to challenge and expand our
culture, work and clients, but we also receive a core capabilities, and we’ve been able to hire
lot of inquiries on our site from prospective into those new projects.
clients, job candidates and press. Truthfully, we “We like to think of ourselves as ambitious,
spend so much more time on our clients’ work since we do aim pretty high. Not to say we
and their websites than we do our own, but I won’t ever take on smaller projects, but they
don’t think that’s unique to a company like are usually a stepping stone into a larger
ours, where we put our heart and soul into our engagement or, more often than not, a project
“ Built upon a history of using clients’ initiatives and strive for continuous or challenge we feel very passionate about.”
digital as the catalyst for larger improvement. That said, we have been working Passion coupled with a deep understanding
organisational change, the projects to overhaul our site and hope to launch a new of today’s digital communications channels
that enable us to take on thought- one soon.” means Code and Theory has been able to forge
As an established agency, Code and Theory a reputation as not only technical experts but
provoking questions that engage
has been able to use its reputation across the also a group of like-minded individuals that
the development of our capabilities marketplace to enjoy a steady stream of clients. shape the digital landscapes we all traverse
are the ones that define who we “We’re fortunate enough to have built a very every day.
are. The types of work we have put good reputation in the industry over the years, Dan explains their typical approach to each
out are intentionally very broad so we receive a lot of referrals from current or unique account they work on: “As a digital-first
across verticals and expressions. former clients as well as inbound inquiries on creative agency, we help our clients across the
We believe that broadness our site,” says Dan. “Additionally, we proactively board to drive change and thrive in a time of
characterises us more than any identify verticals, clients, and most importantly digital disruption – so there really isn’t one
new challenges that we want to work with, as project that encompasses who we are as a
singular piece of work ” well as participate in RFPs (requests for company. Built upon a history of using digital
Dan Gardner proposals) and pitches.” as the catalyst for larger organisational change,
CEO and co-founder With a diverse portfolio of work and clients, the projects that enable us to take on thought-
Code and Theory has been able to choose provoking questions that engage the
which clients they work with. The selection development of our capabilities are the ones
process is detailed, involving a deep dive into that define who we are. The types of work we
the client’s needs in order to understand how have put out are intentionally very broad
the project benefits both the potential client across verticals and expressions. We believe
and Code and Theory. that broadness characterises us more than any
“Typically, we’re very selective to ensure that singular piece of work.”
the relationship with the client is a true fit and As no two accounts are the same, Code and
that we genuinely connect with the company Theory is nothing if not flexible in its approach
and the work,” explains Michael. “We are also to each commission it takes on. David DiCamillo
very realistic about our capabilities and (Partner, Operations) explains how they
resources, so we won’t take on any piece of manage a varied portfolio of clients: “Timelines

34___________________________________________________profile
D e co d e d D e s ig n

NBC NEWS
today.com

THREE BRANDS, ONE


SYSTEM: THE NBC NEWS
DIGITAL REDESIGN
Code and Theory partnered
with NBC News, one of the
oldest and most established
publishers with over 80 years
experience, to revamp their
digital ecosystem. As one
combined team, they worked
across a wide range of areas
to rethink existing paradigms,
including editorial workflows,
design and development
processes, design systems,
advertising integration and
technical approach.
The efforts started small
and focused on the design
and launch of four new
flagship verticals: Mach,
Better, Leftfield and Think.
Work then expanded to
encompass NBCNews.com,
MSNBC.com and today.com.
After the success of
implementing a fresh design
language and strategy, efforts
were turned to NBC’s
Snapchat Show, Stay Tuned,
the first daily news program
of its kind.
As the ever-shifting media
landscape continues to
become more digitally
focused, Code and Theory
re-evaluated why, when and
how people are consuming
news, and sought to find a
way to retain users’ attention
among all the bitesize
content consumption options
available. To do this, Code
and Theory built a highly
flexible set of storytelling
tools that allowed NBC to
focus on creating a strong
editorial voice and bolstering
confidence in their ability to
deliver engaging and
immersive original content to
users, regardless of medium.

“As a digital-first creative


agency, we help our
clients across the board
to drive change and
thrive in a time of
digital disruption”

profile___________________________________________________ 35
D e co d e d D e s ig n

Defining and then creating each customer touchpoint

XFINITY MOBILE
delivered an integrated customer journey

xfinity.com/mobile

When Comcast wanted to enter the fiercely would address challenges related to reflected by the customer and independent
competitive mobile provider market, they in-home activation, custom order logistics, feedback, the final design, experience and
asked Code and Theory to define, design procedural implementation of technology brand integrity scored high marks. The
and develop their mobile offering. They and evolving mobile standards. Solving unboxing experience itself was met with the
needed substantial support – from refining these issues required that essential highest customer acceptance response
the vision and product concepts, information was supplied at efficient across the entire brand journey.
establishing key value propositions and instances, metered through employing an This partnership with Comcast extended
unique selling propositions to deal with the elegantly simple, yet remarkably flexible to nearly every touchpoint for Xfinity
competition and overcome negative unboxing experience. Mobile, defining an end-to-end consumer
marketplace perceptions. In between online order placement and journey. Code and Theory designed and
Xfinity mobile’s e-commerce model successful activation lie a series of logistical developed the complete mobile-first
necessitated the creation of an alternative and user-dependent steps that must be experience and created a packaging system
product experience to contend with those correctly completed. Not only does this based on the unique footprint of the phones
employed by its retail competitors. A process require itself to be concrete, but the themselves – including a special edition for
personalised solution was needed that brand experience must also follow suit. As the first 20,000 customers.

Creating experiences around


a brand is a core design skill
that Code and Theory used
on their work with Comcast

36___________________________________________________profile
D e co d e d D e s ig n

2001
Dan Gardner and Brandon Ralph found Code
and Theory.
Employees: 2

2002
Code and Theory develops the first-ever Flash
Player website, for Sony Classical, and create the
first Flash videos for Sony Music, setting off years
of Flash video being the dominant way to consume
online video.
Employees: 3

2006
Code and Theory opens its San Francisco office,
brings one of the first large-scale content
catalogues online for Charlie Rose and launches
the largest online live streaming events in history
at the time for Dr. Pepper.
Employees: 15

2007
The vertigo-inducing Working beyond digital, Code and Theory launches
view from the Code an animation series in partnership with McCann
and Theory offices in Erickson for the Subway.
New York Employees: 15

2008
and process vary greatly depending on the prototype in InVision or Principle based on the Launch of The Daily Beast , bringing together core
scope of a project. However, every single one of fidelity of the prototype that we need to create. strengths – advertising and content delivery – to
our projects is structured around a tight and Sketch actually slowly worked its way into our execute the vision of Tina Brown and Barry Diller to
dedicated interdisciplinary team we call ‘Pods’. design process a few years ago, after putting it reimagine online news and advertising.
Employees: 15
“The Pods consist of, but are not limited to, through a lot of testing. There was a kind of
skills such as Creative Strategy, Production, breaking point with Sketch through one
Content Strategy, Experience Strategy, particular software update in which almost 2012
Interaction Design, Visual Design, Data/ everything we were waiting for was Mashable: first-ever page-to-page continuous
scroll on (‘The Transporter module’) launches,
Analytics and Technology. When the project implemented all at once, so we immediately
which is now standard behaviour on most
requires additional scale or speciality outside switched over to Sketch. publishing platforms (a world first).
the Pod, we add Flex Resources based on the “Prior to Sketch, we were using Photoshop or Employees: 15
requirements of the project phase. Within a InDesign for our responsive design work, which
Pod, we designate someone as the Directly sometimes caused friction between projects 2013
Responsible Individual (DRI) to help drive and designer taste. Both Photoshop and Code and Theory establishes its Industrial Design
leadership and vision across the team to InDesign did the job just fine, but neither were practice, the first digital-first agency to move into
prevent ‘design by committee’ decision- truly built for modern digital design needs. physical hardware design.
making, as well as ensure accountability for There was a grey area missing in the tools we Employees: 15
project success.” were in need of that Sketch filled for us. There
David concludes: “Depending on the scale are a number of reasons why we are sticking 2014
and complexity of a project, the time- with Sketch, but what stands out the most is Launches its first 23 magazine solution (Hearst:
consuming part can vary. Sometimes that is how much more productive we have become Cosmo, Esquire , Elle , Good Housekeeping , etc.).
more in the strategic upfront to identify or as a team since using it. It has greatly Launches the first Olympics site for the Sochi
Winter Games (NBC). Launches latimes.com, at
solve the problem, or sometimes it could be in streamlined designing across platforms, to the time the largest fully responsive news site in
the technology if there is some complexity or exporting assets, to working faster with the world.
scale in the digital expression of the solution. developers. Unlike the Adobe suite of products, Employees: 15
Most importantly, we don’t let process dictate Sketch was built specifically for what we do in
an outcome to get to success – we use process the product design space.” 2015
as a facilitator to success.” Chris concludes: “We have also done away Code and Theory is named one of Fast Company’s
As an agency that creates digital with the time-consuming style guide process. 10 Most Innovative Companies in Design for work
communication assets that both fulfil their which used to eat up a lot of time and money, creating publishing platforms. Code and Theory
client briefs and also advance the digital by adopting Zeplin app into our process, which acquires Mediacurrent.
Employees: 15
environment, Code and Theory has a varied has cut the style guide production time down
toolset it wields with absolute confidence, as by 90 per cent. For content creation, we will
Chris Delia (Group Creative Director) explains to use the Adobe suite. This is anything from 2018
Web Designer: “Our product design work is photo composites, touch-ups, GIF creation, Code and Theory moves its NY HQ to 1 WTC
Employees: 310
strictly done in the Sketch app, while we video effects, etc. For 3D we use Cinema 4D

profile___________________________________________________ 37
D e co d e d D e s ig n

Ren Vasey (Content


Strategist) and Asli
Aydin (Creative
Product Strategist)
discussing their
latest client brief

and SketchUp. That said, we are a company that


embraces change and improvement, so we are
always open for an evolution in tools.”
Using the latest tools to advance its vision for
a client is commonplace across Code and
Theory. Chris continues: “Whether we are
considering tightly coupled or decoupled
architectures, there is a growing tendency for
8X ADMIN

3
4X
X

2XC

websites to embed more of their logic on the


B
C
U
42 X

9XC
L
S
I
O
IN
E

client side. As such, the frontend technologies


N
N
VISU

ESS DEVE

O
T
T SERV EGY
ENT S

P YWR

have to not only accommodate for advanced


AL D

TRAT
ICES

ITIN

animations, interactions and responsive or fluid


ESIG

LOPMEN

29
N

CR X design in an increasingly complex device or


EA
T

TIV
ES browser environment, but they also have to
TR
AT
EG
account for more elaborate rules and flows.
Y “JavaScript is evolving quickly to be on par
with these expectations: ES6 is introducing
10 X
DATA advanced notions, such as collections,

AGENCY
, ANA
LYTIC promises, advanced inheritance, etc. that bring
S, RE
SEAR
CH it closer to more traditional languages. This is
8 X EXPE
RIENCE S all meant to allow for more complex

BREAKDOWN
TRATEGY
experiences, which in turn means that these
technologies will be more prevalent in the
future. Frameworks such as AngularJS and
74XTECHNOLOGY
17 X FINANCE React are already used by most major sites, in
order to capture data from different sources
and render the right experience for the user.
ESIG
N Others, such as Three.js or D3.js, help
4 X HR IAL D
DUS T R developers create visually engaging
PLUS 70 EMPLOYEES AT 2 X IN
MEDIACURRENT, WHOLLY OWNED DES
IGN experiences with advanced visual effects.”
N
SUBSIDIARY AGENCY FOCUSED ON TIO AC Mobile digital devices have clearly had a
TER
OPEN SOURCE (DRUPAL) X IN
19 profound impact on digital communications.
T
EN

Laurent Pierre (CTO) explains how Code and


EM
NT AG

Theory approaches these technologies: “As a


ME AN
UIT E M

T
EN
NCE

pioneer in mobile and responsive design across


CR RC

AL

IT
EM
RE OU

EG

2X
URA
3 X RES

industries, Code and Theory was among the


2X
NA
2X

ASS

MA

first companies to design and deliver large-


X
LITY

DUCTION

scale, responsive experiences in publishing


QUA
23 X

(Los Angeles Times, the largest fully responsive


38 X PRO

newspaper in the United States), e-commerce


(Moda Operandi, the first fully responsive

38___________________________________________________profile
D e co d e d D e s ig n

Tavit Geudelekian (Associate Director of Creative Strategy),


Alexis Baran (Creative Product Strategist and Designer), “To us, responsive design is
Alexa Varsavsky (Associate Director of Creative Strategy), about more than just responding
Erika Templeton (Associate Director of Content Strategy),
Thomas Strickland (Associate Experience Strategy Director) to the user’s device. Leveraging
and Nikhil Bhasin (Senior Engagement Manager) at work what we know about a user, we
layer onto their experience
luxury shopping experience targeted at agile spaces that consumers now move through.
mechanisms of adaptation that
high-net-worth clients), and mobile video An appreciation of the link between great present the content, services,
consumption (MobiTV, at the time the largest design, storytelling and a command of the latest product offerings and resources
white-label mobile video provider). tools ensures the brands it works with are able most relevant to them ”
“To us, responsive design is about more than to innovate, astonish and understand their
just responding to the user’s device. Leveraging customers with well-crafted messages. Laurent Pierre
what we know about a user, we layer onto their As Dan concludes, Code and Theory is a Chief Technology Officer
experience mechanisms of adaptation that business that constantly pushes at the
present the content, services, product offerings envelope of what digital design means today:
and resources most relevant to them.” “We continue to look at ways we can service
As an agency that doesn’t stand still, Code our clients from the perspective of ‘the user’
and Theory always has an eye on the future, as and marrying that to business opportunities, so
Dan outlines: “Powerful processing and our agency’s only limitation is our own
accessible cloud computing have also allowed creativity and not just tactical capabilities.
us to utilise artificial intelligence in various “Change is the constant, so we don’t expect
experience formats. Computer vision, machine tomorrow’s Code and Theory to be the same as
learning, natural language processing, etc. are today’s, and that is what excites us. As for
now all available for us to use at the mobile exciting upcoming projects, you’ll have to wait
device level, and in turn we are able to create and see
see.”
more tailored experiences for the user by
bringing together a more contextually coheren nt
experience. The access to readily available
tools such as Google Cloud ML services and
TensorFlow allow us to train our own models
and are tools to help us to solve problems and
create new ways for our applications to interacct www.codeandtheory.com
with users.
“And finally, there has been a great Fo u n d e r s S e r vice s
innovation in the creative development realm Dan Gardner
where tools such as Cinder, openFrameworks Brandon Ralph Data and Analytics
and TouchDesigner are paving the way to
create all sorts of new physical and device- Ye a r Fo u n d e d Platforms
based experiences. These software programs, 2001 and Products
along with hardware micro-controllers and
Curre nt Em p l oye e s
sensors, allow us to create things that connect
the digital and physical world in ways we have
310 Integrated Marketing
not been able to before.” Lo c atio n Connected Experiences
Code and Theory is a multifaceted agency New York, USA | London,
that clearly understands what digital England | San Francisco, USA Business and
communications means today. Not content with h | Manila, Philippines Organisational Consulting
following trends, this agency actively creates

profile___________________________________________________39
CSS Conic gradients
animation
6 0 fp s
int API
CSS Pa
B E C O MEA
sso r
roce

prep
NEED TO

CSS Layo
OOCSS, ACSS, SMACSS or BEM?
u t API
ms interview
y Willia
ssid

CSS
Ca

Tra
nsform
s
U

les

40 _________________________________________________feature
O

A n im ation API CSS Variab


L Y
s
rame
L

Com
A
f
key

bi n
CSS

e me
tho
CSS Clip path
dolog ies
ans i t ions Grid &
r
C SS t ac

ces
sibil
ity
ate -rows
m p l

What’s inside?
-te

grid St
ory
bo a r
ding

Welcome to our CSS special


issue. Take a look at what’s
on offer
fr measu
re

42 CSS animation
me

Explore everything from reasoning and


nt u
ts
n it planning to implementation

c u to u
lay 52 Build with CSS Grid

Di sp Learn how to build basic grids before moving


on to more advanced techniques

58 Optimise your CSS


Discover a host of tips and techniques to make
Wha

your CSS blazingly fast


t is Ho

64 Style with Sass


Power up and extend your CSS with the popular
udini?

preprocessor Sass

68 Create CSS art


CodePen engineer Cassidy Williams reveals how
to create CSS art and offers some useful advice

72 Best CSS methodologies


Ahmed Abuelgasim explains what CSS
methodologies are and how to use them
An

76 Cutting-edge CSS
i m

The hot properties and APIs that you should be


a

using today. Plus a peek at the future


te SVG

feature _________________________________________________ 41
CSS ANIMATION

ANIMATION IS AN IMPORTANT PART OF MODERN UX AND IS EASIER THAN EVER


TO IMPLEMENT WITH CSS. IN THIS FEATURE WE’LL EXPLORE EVERYTHING
FROM REASONING AND PLANNING TO IMPLEMENTATION

While it may seem limited or a lesser tool


when it comes to animation, CSS is actually a really
powerful tool and is capable of producing beautifully
smooth 60fps animations
Steven Roberts, Head of UX, Asemblr.com
@matchboxhero10 codepen.io/matchboxhero

42__________________________________________________feature
CSS ANIMATION

BEFORE YOU BEGIN


Planning your animations and knowing when to use them can be
just as important as the animation itself

WHERE TO USE ANIMATIONS


Animations can become as important to
STORYBOARDING
your brand as your primary colour or logo.
--------------------------------------------------------------- QUICKLY PLAN YOUR ANIMATION’S FLOW important for deciding if your panel edge will
Storyboarding is a technique used in many be visible or not. If you don’t want it to be
ANIMATE INTERACTIONS FOR disciplines and industries. It is, for example, visible you need to keep everything in frame
BETTER UNDERSTANDING used for video games, TV shows, movies, at all times.
Sudden changes to the state of your music videos and any other discipline with a
application or website can be jarring and narrative and visual element to it. Arrows: Arrows in storyboarding are used to
can easily cause confusion. Animating convey movement, showing the direction an
interactions is a great way to help the user element will be moving.
understand the change of state. WHAT IS STORYBOARDING?
--------------------------------------------------------------- Storyboards are illustrations of the key
frames or elements that will make up the HOW DO I CREATE STORYBOARDS?
DELIGHT YOUR USERS WITH final works. This allows for ideation of visual There are no solid rules when it comes to
MEMORABLE EXPERIENCES elements, which would take a lot of time to storyboarding, and you don’t need to be able
Animation can be used to provide delightful produce in full, to be quickly, easily and to draw either. The idea is to convey the
experiences. You don’t need to go cheaply captured. timeline using as few sketches as you can.
overboard – something small and subtle can You can annotate your panels in order to
create a memorable experience, which can explain certain features of your animation
keep users coming back. WHAT ARE THE ELEMENTS OF A STORYBOARD? where needed.
---------------------------------------------------------------
Panels: Panels are the viewport for your
INFORM USERS WITH animation. Your panels can be any size or WHY STORYBOARD FOR WEB ANIMATIONS?
PROGRESS INDICATORS shape you want, but need to match the If you’re creating anything more than a
Progress indicators should be animated to container size and aspect ratio when you put simple transition, storyboarding the
inform the user that the system is still them into the browser. elements can save you a lot of time. Before
responding. Users have come to expect you even write any code, you understand
immediate feedback; when submitting data Framing and composition: This is how to break down the elements involved
or loading content, a simple spinner can be choosing where in your panel to place the and where each of the key frames of your
enough to keep their attention. elements you’re going to animate. This is animation should lie on the timeline.
---------------------------------------------------------------

USE PERCENTAGES TO
REPRESENT PROGRESS
Percentages when used to represent
progress are a great place to use animation.
Watching a bar or shape fill up is rewarding;
visually representing a user’s goal can
subtly encourage them to complete it.
---------------------------------------------------------------

DON’T ANIMATE EVERYTHING,


IT’S NOT NEEDED
It’s important to know how and when to use
animation. You don’t want to animate all the
things and create the mess that GeoCities or
MySpace became. Animation should be
used sparingly.
---------------------------------------------------------------
Simple storyboard sketch showing how an interaction with a record player could animate

feature _________________________________________________ 43
CSS ANIMATION

CSS TRANSITIONS
CSS transitions can be used to achieve a number of animated
effects, from a simple colour change to more complex transitions

WHAT IS A TRANSITION? TRANSITION-TIMING-FUNCTION


Put simply, transitions are a way to provide Timing functions or easing enable us to WHAT ABOUT BROWSER
SUPPORT?
animation between two property values. For adjust the rate of change over time. There
the animation to trigger, something needs are a number of keywords we can use. For
to change in the application or website. example, the ‘linear’ keyword will transition
-------------------------------------------------------------- from A to B at an equal temperament, Support for transitions and animations in
whereas ‘ease-in-out’ will start slowly, speed modern browsers is really good. Everything
HOW DO TRANSITIONS WORK? up in the middle and slow down towards the from Internet Explorer 11 or above is going
Transitions in CSS are simple, we just need end. Custom timing functions can also be to support the majority of the code needed
to choose what elements to transition and defined using the ‘cubic-bezier’ property. A for animation.
when. For example, if we have a button and full list of timing keywords can be found at There are exceptions with some of the
we want to change the background colour https://mzl.la/2OXGB0e. newer animation properties; CSS Motion
gradually instead of instantly when the user --------------------------------------------------------------- Path, for example, or when using SVG or
hovers over the button, we use a transition. custom properties (CSS variables) as part
.button {background-color: Crimson; TRANSITION-DELAY of the animation.
transition: background-color 500ms;} Transitions can be delayed using this property
.button:hover {background-color: DarkRed;}
--------------------------------------------------------------
and is set using seconds or milliseconds.
--------------------------------------------------------------- DO I NEED TO USE
TRANSITION SYNTAX TRANSITION SHORTHAND
PREFIXES?
Transitions in CSS are made up of four All of the transition properties can be Prefixing for the most part is probably not
properties, giving us control over how the combined into a shorthand statement using needed unless we need to provide support
transition will animate. the ‘transition’ property; for older browsers – Internet Explorer 10
-------------------------------------------------------------- transition: property || duration || and below.
timing-function || delay; There are several ways we can prefix
TRANSITION-PROPERTY transition: background-color 500ms linear code if needed. Auto-prefixer
The ‘transition-property’ property enables 250ms; (autoprefixer.github.io) is a really useful
us to choose which properties we want to We are free to omit the values we don’t tool that can be used as part of a build
animate. We can transition a number of need in order to set the defaults. process or manually at the end of a project.
different properties. A full list can be found --------------------------------------------------------------- It enables us to configure the browser
online at https://mzl.la/2BpQJet. support you need, then it will automatically
-------------------------------------------------------------- COMBINING TRANSITIONS prefix our code where needed.
You can combine multiple transitions to We can also check the support for any
TRANSITION-DURATION create choreographed animations. Check property using the amazing tool ‘Can I Use’
The ‘transition duration’ property enables us to this example: (caniuse.com). Simply type in the property
control how long the transition from one transition: we want to use and see which browsers
property value to another will take. This can be background-color 500ms linear, are supported.
defined in either seconds (s) or milliseconds (ms). color 250ms ease-in 250ms;

HAMBURGER ICON LARGE TEXT MENU CIRCULAR MENU ANIMATED CORNERS


http://bit.ly/2S8ptXl http://bit.ly/2PPp3bZ http://bit.ly/2QaWIMG http://bit.ly/2FwujfI

Upon hover the colour changes The menu items light up The middle icon changes colour The triangular corner is animated

44 _________________________________________________feature
CSS ANIMATION

CSS KEYFRAMES
CSS keyframes are used for complex or repeatable animations

WHAT IS A KEYFRAME ANIMATION? PERCENTAGE ANIMATIONS ANIMATION-DIRECTION


Keyframe animations in CSS enable us When creating animations where we need When applying our animations, we have the
to define multiple property values to to define more than one point to animate, ability to play them back in a number of
animate between. Keyframe animations we can use percentages. This enables us to ways. The default value is ‘normal’, which
can be reused and repeated, unlike have precise control over our animation. will play the animation forwards. We can
CSS transitions. @keyframes flash { also play the animation in reverse or
-------------------------------------------------------------- 25% { opacity: 1; } alternate the animations playing forwards
27% { opacity: 0.4; } and backwards.
DEFINING KEYFRAME ANIMATIONS 29% { opacity: 1; } --------------------------------------------------------------
CSS keyframe animations are defined using 31% { opacity: 0.4; }
the ‘@keyframes’ syntax. This works much 75% { opacity: 1; } ANIMATION-FILL-MODE
like a media query where we nest elements } The fill mode value enables us to choose
inside of the ‘@’ statement. Inside the -------------------------------------------------------------- what should happen at the end of an
keyframe declaration we have two options: we animation to the value that we have
can use the keyword ‘to’ and ‘from’ or we can APPLYING OUR ANIMATION changed. For example, setting the value to
define our timeline using percentages. Animation in CSS has a number of ‘forwards’ will keep the property values
-------------------------------------------------------------- properties we can set in order to have from the end of the animation, whereas the
precise control over the playback of our default value ‘none’ will return the elements
KEYWORD ANIMATIONS keyframe animations. Some, like ‘animation- to their original state after the animation
When the animation we’re creating only has duration’, ‘animation-delay’, ‘animation- has finished.
two points to animate between, we can use iteration-count’, ‘animation-play-state’ and --------------------------------------------------------------
the ‘to’ and ‘from’ syntax, in fact we can use ‘animation-name’ are all fairly self-
just ‘to’, providing the original property explanatory, while some of the other ANIMATION SHORTHAND
value is set on the element we’re going to properties can be a little trickier to learn All of the animation properties can be
be animating. and utilise to their full potential. combined into a shorthand statement using
#record { -------------------------------------------------------------- the ‘animation’ property. We are free to omit
transform: rotate(0deg); the values we do not need and want to leave
animation: rotate 1s; ANIMATION-TIMING-FUNCTION as the default values.
} Timing functions in animation are the same animation: duration || timing-function ||
as transitions whereby we can use either delay ||
@keyframes rotate { keywords or set a custom timing function
to { by using the ‘cubic-bezier’ value. A full list iteration-count || direction || fill-mode ||
transform: rotate(360deg); of timing keywords can be found at play-state || name;
} developer.mozilla.org/en-US/docs/Web/
} CSS/animation-timing-function animation: 500ms linear infinite flash;
-------------------------------------------------------------- ----------------------------------------------------------- --------------------------------------------------------------

feature _________________________________________________45
CSS ANIMATION

ANIMATION PERFORMANCE
Animating too much or too many properties will cause animations to stutter

Page speed and performance is an properties are ‘transform’, ‘opacity’ and


important aspect of any application or also ‘filter’. TIMING AND
website. If you are using animation as part
of your project, it can be a good place to
The reason for this is that animating any
other property will cause the browser to CHOREOGRAPHY
start when trying to optimise performance. have to repaint the page, and this is an
Firstly you can check that you’re not expensive process in terms of performance
using too many animations all at once on and will likely take longer than 16.7ms to Utilising the correct timing and delays will
the page: as well as being bad for calculate and draw each change. produce much better-looking and
performance, it is also bad for your users’ --------------------------------------------------------------- easier-to-comprehend animations. When
experience. Multiple animations on different animating any elements, it’s important to
parts of the page will be fighting for their GIVING THE BROWSER choose a duration that is appropriate to its
attention as well as potentially causing A HELPING HAND context. For example, an animation that’s
performance issues. Being aware of the We can also utilise the ‘will-change’ applied to a button interaction should be
number of animations will help to address property in order to give the browser a short, usually less than a second.
both of these potential issues. heads up that this property is going to Utilising long animations for common
--------------------------------------------------------------- change. This enables the browser to interactions is tedious and annoying to the
perform some optimisations before your user and can make your application or
AVOIDING JANKY ANIMATION animation even starts. website feel sluggish and slow. However,
In order to achieve a smooth 60fps --------------------------------------------------------------- providing an animation duration that is too
animation, the browser has only 16.7ms short can cause confusion and provoke the
(1000ms/60) to achieve all of the work that THE FUTURE OF WEB ANIMATION wrong emotions and feelings for your
needs to be done per frame. If the browser PERFORMANCE audience. Once you have chosen a
can’t complete all of the operations needed, The new Firefox Quantum project is taking comfortable animation duration, you
it will stop and move on to the next frame, amazing strides towards making every should use this in every aspect of your
starting the calculation and redrawing animatable property perform well, as well website or application.
process all over again. This is when we start as many other improvements to rendering When animating, multiple elements or
to see dropped frames, causing janky or content on the web. property delays should be used to
stuttering animations. It’s also worth noting that the newest enhance comprehension. It’s much easier
While the list of animatable properties is versions of the iPad will play animations to see what’s happening in an animation
extensive, at the moment we can only safely back at 120fps, which will reduce the time in when one thing happens at a time instead
animate a handful of these properties to which the browser has to calculate and of all at once.
keep within the necessary 16.7ms. These paint each frame to 8.35ms.

46 _________________________________________________feature
CSS ANIMATION

ANIMATING SVG
SVG enables us to create intricate drawings and images, where all of the elements
inside SVG are also animatable using CSS

USING CUSTOM PROPERTIES


CUSTOM PROPERTIES, OR CSS
VARIABLES, CAN BE USED TO
CREATE CONFIGURABLE PARTS OF
YOUR ANIMATION

PREFERS REDUCED MOTION


Animations and movement can cause
SVG has many benefits – its vector nature is in order to set the point at which a transform motion sickness in some users. We can use
great, and we don’t get any of the problems operation takes place. custom properties in order to effectively
we get with bitmap images when displaying transform-origin: 50% 50%; remove animations for users who have
an image too big or too small or on devices transform-origin: center center;} indicated preferring reduced motion.
with differing DPIs. SVG is also much :root {
smaller in size. SVGs are basically So if we can’t use keywords and can’t use --timing: 500ms;
instructions for the browser to draw the percentages, how do we set our transform }
image contained within. origin? The answer is to use pixel values. @media (prefers-reduced-motion: reduce) {
--------------------------------------------------------------- Further complications come into play --timing: 0;
because, unlike regular elements that would }
HOW DO I ANIMATE SVG? measure the pixels from the top left corner .animate {
Animation in SVG works exactly the same of itself, SVGs will measure from the top left animation: my-animation var(--
way as it does with any element on the corner of the parent SVG canvas. Jack Doyle, timing) linear;
page. We need some way to target the author of the GreenSock Animation Platform, }
element we want to animate, and then apply has written a blog covering this topic in By changing the timing to ‘0’, we stop the
the animation. detail on the CSS Tricks blog; css-tricks. animation from running when the user
svg rect { com/svg-animation-on-css-transforms has requested it. While this media query
animation: 2s linear infinite rotate; --------------------------------------------------------------- isn’t yet widely supported, it is by iOS.
}
--------------------------------------------------------------- BROWSER SUPPORT CHANGING OTHER PROPERTIES
CSS animation when used with SVG requires We can use custom properties to define
GOTCHAS the SVG to be inline in the page for the other parts of our animation, such as the
The main way in which animating SVG majority of browsers. This means we can’t colour or size and use. This is useful if we
elements differs from regular elements is use the image tag to include our SVG and have a part that’s configurable and we’re
the ‘transform-origin’ property. Normally we perform animations; we need to have our using that property as part of an animation.
would use percentages or keyword values SVG inside an SVG tag on the page.

WEB DESIGNER MAG 268 – SVG SNOW SVG BUBBLESV


CSS ANIMATED COVER

codepen.io/matchboxhero/pen/ codepen.io/matchboxhero/pen/JrLJeb codepen.io/matchboxhero/pen/LzdgOv


qVWNZo

feature _________________________________________________ 47
CSS ANIMATION

BRING IT ALL TOGETHER


In this tutorial we’ll look at how we can combine all of the elements we’ve
covered in the article into one single animation

1 2

The initial state of the animation, with the arm placed off the record The first thing that happens is the arm moves into position over the
and the record not moving record, and halfway through this animation the record begins to spin

3 4

Once our arm is in position and the record has rotated slowly once, we When the user stops interacting the record spins backwards slowly and
then spin the record faster, infinitely the arm moves back to its original position

We’ll be creating a record player animation OPTIMISE OUR SVG transform-origin: -1px 11px;
where the arm of the record player moves When we have the exported code from our }
into position over the record, as well as editor we need to optimise that code to #record-container {
rotating the record itself at two different make it easier for us when creating our transform: translate(7px, 0)
speeds. We’ll create the animation using animation. Firstly we’ll run it through rotate(0deg);
SVG transitions and keyframes, and we’ll be SVGOMG (jakearchibald.github.io/ transform-origin: 24px 24px;
using custom properties in order to make svgomg) making sure to only optimise the }
our animation configurable. parts we need. Once we’ve done this we’ll #record {
paste our code into CodePen and create transform: rotate(0deg);
CREATE AND EXPORT OUR SVG some basic page styles. We’ll be using Sass transform-origin: 24px 24px;
The first step is to create and export our to take advantage of the nesting capability. }
SVG code. You can do this using many https://bit.ly/2PZVbd6 https://bit.ly/2r7alya
different graphics editors (the example is
Sketch for Mac). The shapes being used are -------------------------------------------------------------- --------------------------------------------------------------
simple – mostly straight and poly lines
combined with circles. We want to create EDIT BY HAND ANIMATE THE ARM
the SVG in the initial state of our animation. Next we will need to edit our SVG by hand. We can achieve most of what we are trying
We are going to need to remove any inline to do using transitions. We will start with
transforms on elements that we are going the record arm and animating the arm into
to animate into our CSS. Doing this will position over the record. To do this we will
make it easier to animate, because we’ll be need to rotate the arm of the record from
able to see all of our transform properties in ‘-90deg’ to ‘0deg’. In order to transition
one place. rotation we need to use the transform
#arm-top { property. This means we also need to keep
transform: translate(9.5px, 3px) any other transform properties the same
-------------------------------------------------------------- rotate(-90deg); when changing the rotation.

48 _________________________________________________feature
CSS ANIMATION

#record-svg:hover, #record-svg:active, IN REVERSE CONFIGURABLE DURATION


#record-svg:focus { Everything is working now and our We can utilise the ‘calc()’ function in order to
animation is complete – until the interaction make the animation duration configurable.
#arm-top { stops. At that point, both the arm and record Firstly we need to set a new custom property
transform: translate(9.5px, stop animating and jump back to their for our duration with a value, in seconds. We
3px) rotate(0deg); original positions. This is where the setup of can then use this value in order to set all of
transition: transform 1s; our SVG is important. The record element the other animation time values.
} itself sits inside of a container. By animating transition: transform 500ms;
} the container using a transition we can also Given the custom property ‘—animation-
https://bit.ly/2Qkew7Y perform another transition in reverse with duration’ being two seconds becomes;
just a couple of lines of code. transition: transform calc(var(--animation-
duration, 2s) / 4);
SLOWLY ROTATE THE RECORD #arm-top { By doing this for every time value in our
Next we can use another transition to ... animation, we can control the speed of the
complete the first, slower rotation of our transition: transform 500ms; entire animation by simply changing the
record. To do this we will need to target the } custom property at the top of our CSS.
container and apply our transition code, #record-container { https://bit.ly/2RjsULb
much like we did in the previous step, ...
except this time we will be adding a delay of transition: transform 500ms linear; --------------------------------------------------------------
a quarter of the time it takes for the arm to }
move into position. https://bit.ly/2TJMhhM OPTIMISATIONS
#record-svg:hover, #record-svg:active, Now we can add our accessibility options for
#record-svg:focus { -------------------------------------------------------------- ‘prefers-reduced-motion’ and add the
‘will-change’ property to all of the elements.
#record-container { CUSTOM PROPERTIES https://bit.ly/2SaFfRJ
transform: translate(7px, 0) Now we’ve got our complete animation, we’ll
rotate(360deg); make it configurable with custom properties.

1s 500ms linear;
transition: transform We can do this by setting our custom
properties on the root element in our CSS. TWITTER ACCOUNTS
}
}
:root {
5 TO FOLLOW
https://bit.ly/2Rcpw4r --background-color: #2A2A2A;
--record-colour: white;
SARAH DRASNER
-------------------------------------------------------------- --record-size: 12rem;
} @sarah_edo
SPEED UP THE ROTATION Sarah is the author of the O’Reilly book
In order to speed up the rotation, and for it We can then apply them to the property SVG Animations .
to repeat infinitely, we’ll need to use a values where needed, making sure to
keyframe animation. The animation we need provide a fallback for each one. RACHEL NABORS
to create is simple, we just need to rotate .container {
@rachelnabors
the record 360 degrees. max-width: var(--record-size, 15rem);
@keyframes rotate-record { max-height: calc(var(--record-size,
Interactive storyteller, cartoonist and
to 15rem) * 1.166); author of Animation at Work .
{ ...
transform: rotate(360deg); } VAL HEAD
} @vlh
} We can also use custom properties as part Author of Designing Interface Animation
Then when we’re applying our animation, of ‘calc()’ functions, which is particularly
and curator for ‘UI Animation Newsletter.
we need to make sure to set the delay useful for sizing and for creating durations
correctly so our animation starts at the end and delays.
of the container stopping. LISI LINHAR
#record-svg:hover, #record-svg:active, @lisi_linhart
#record-svg:focus She is passionate about web animation
{ and talks about ‘Practical Web Animation’.
#record {
animation: 400ms linear
CODEPEN
1250ms infinite rotate-record;
}
@CodePen
} Tweets great examples of animation that
https://bit.ly/2zsKhCe https://bit.ly/2zq9xck have the code for you to learn from.

feature _________________________________________________49
The perfect gift
*
from just £24.99
PLUS

FREE
KITSOUND
RACE
WIRELESS
EARPHONES
WORTH
£14.99

Order hotline 0344 848 2852


Please quote xmas182 when ordering by phone
Lines open Monday to Friday 8am-7pm and Saturday 10am-2pm (GMT)
FR

SU J y 6
O e
M ver
B US m o
SC T nt
R £2hs*
IB 4
Reasons

E .9
to subscribe

9*
Saving up to 41%
against the shop price
Never miss an issue
Free delivery to
your door
The gift that keeps
delivering

Upgrade to
include digital
for only £5
Increase your
saving to 63%

SEE THE
FULL RANGE AND
ORDER ONLINE AT
www.myfavouritemagazines.co.uk/pin/xmas182
Call UK 0344 848 2852 or overseas‫גגڷ‬٨‫׎‬٩‫ۭאדזאזגזגגב‬quote xmas182

*Terms and conditions: Savings calculated against the full RRP (single issue price x frequency). You can write to us or call us to cancel your subscription within 14 days of purchase.
Gift is only available for new UK subscribers. Gift is subject to availability. Please allow up to 60 days for the delivery of your gift. In the event of stocks being exhausted we reserve the right
ɎȒȸƺȵǼƏƬƺɯǣɎǝǣɎƺȅɀȒǔɀǣȅǣǼƏȸɮƏǼɖƺِçȒɖȸɀɖƫɀƬȸǣȵɎǣȒȇǣɀǔȒȸɎǝƺȅǣȇǣȅɖȅɎƺȸȅɀȵƺƬǣˡƺƳƏȇƳɯǣǼǼƺɴȵǣȸƺƏɎɎǝƺƺȇƳȒǔɎǝƺƬɖȸȸƺȇɎɎƺȸȅِ¨ƏɵȅƺȇɎǣɀȇȒȇ‫ٮ‬ȸƺǔɖȇƳƏƫǼƺƏǔɎƺȸɎǝƺ‫ג׏‬ƳƏɵ
ƬƏȇƬƺǼǼƏɎǣȒȇȵƺȸǣȒƳɖȇǼƺɀɀƺɴƬƺȵɎǣȒȇƏǼƬǣȸƬɖȅɀɎƏȇƬƺɀƏȵȵǼɵِçȒɖȸɀɎƏɎɖɎȒȸɵȸǣǕǝɎɀƏȸƺȇȒɎƏǔǔƺƬɎƺƳِǼǼǕǣǔɎɀɖƫɀƬȸǣȵɎǣȒȇɀɯǣǼǼɀɎƏȸɎɯǣɎǝɎǝƺˡȸɀɎǣɀɀɖƺǣȇhƏȇɖƏȸɵ‫¨ِח׏׎א‬ȸǣƬƺɀƬȒȸȸƺƬɎƏɎȵȒǣȇɎ
ȒǔȵȸǣȇɎƏȇƳɀɖƫǴƺƬɎɎȒƬǝƏȇǕƺِIɖǼǼƳƺɎƏǣǼɀȒǔɎǝƺ(ǣȸƺƬɎ(ƺƫǣɎǕɖƏȸƏȇɎƺƺƏȸƺƏɮƏǣǼƏƫǼƺȒȇȸƺȷɖƺɀɎِIȒȸǔɖǼǼɎƺȸȅƏȇƳƬȒȇƳǣɎǣȒȇɀȵǼƺƏɀƺɮǣɀǣɎ‫ي‬ƫǣɎِǼɵٖȅƏǕɎƏȇƳƬِ ǔǔƺȸƺȇƳɀ‫׏ב‬ɀɎ(ƺƬƺȅƫƺȸ‫ِז׏׎א‬
CSS GRID ENABLES YOU TO DEFINE ADVANCED CONTENT LAYOUT FOR
RESPONSIVE DESIGN WITHOUT THE COMPLICATED FORMATTING

CSS grid offers more flexible definitions for


content layout. Unlike older alternatives, such as table
layouts and floating elements, grid has been designed
to benefit SEO, responsive design and accessibility
Leon Brown
twitter: @LeonBrown

52 __________________________________________________feature
CSS Grid

WHY YOU NEED CSS GRID IN YOUR LIFE


CSS Grid lets you create advanced layouts while focusing on the user

To some, a wireframe may seem


like a laborious and unnecessary
wireframe, but what should be
added? This is where the core
a pastel blue background will
present them as the important
WHAT ABOUT
task that can drag out a project
with no real long-term benefit.
components are decided and
added to the wireframe — the
elements in your component.
It’s also important to consider a
FLEXBOX?
Jumping straight into a design components that the design can’t grid system, padding and margins
may seem like a compelling and live without. as soon as possible when defining Flexbox is another option that
rewarding alternative, but by doing Starting with the header, what the wireframes. Showing rulers in can be used to control the
so you could be forgetting the do we need if we are approaching a Sketch file and clicking on these flow of content. The main
most important thing of all when this project mobile first? Is the rulers (down the left and above difference is that it was
creating a design: the user. logo the main focus? Should we your artboard) will create guides, created specifically for
The ideation and wireframing consider using a ‘burger’ which in turn saves a lot of stress one-dimensional content flow,
stage of any design enables you navigation to ensure best practice? when sharing designs, as whereas grid is used for
to consider the layout and user These are the questions any consistency is key when defining two-dimensional purposes.
experience from the very start of designer should keep asking a design system. While flexbox gives you the
your project. By only using the themselves throughout the When the essentials are in place option of controlling the
core components for your web process when building their for one component, move onto the horizontal or vertical layout,
design — header, footer, wireframe components. next. Only include what you need. CSS Grid controls both
navigation, buttons — to begin The first steps should be to Keep in mind the bare minimum horizontal and vertical layout.
with, you can always ensure your create an artboard for mobile or that is needed for the user to In effect, you can consider
focus is on the user, without desktop, and begin to build the complete their task. Planning to CSS Grid to be the next step
getting distracted by which colour components on the page with use these components in more up from flexbox.
palette you had in mind. simple shapes in order to define than one artboard? Why not create Although the grid feature
There are plenty of tools out the outline of the components like a symbol. Symbols act as super- can be used to define any
there to get started with the header. To highlight areas of components that update all the type of layout, flexbox
wireframing, but today many web importance and interactivity in the artboards they currently sit in. To provides the advantage of
teams use Sketch. Its usability and wireframe, use varying shades of a create a component, right-click an keeping your CSS simpler for
unrivalled speed make it the monochrome colour palette while element and choose ‘Create one-dimensional layout. It’s
obvious choice. wireframing. For example, within symbol’. This will be saved into one worthwhile keeping in mind
So a project has been set up and the header, inserting a logo and packaged item manageable from that requirements may
a font has been chosen for the navigation in a bold blue colour on the symbols page. change or expand to include a
requirement for two-
dimensional layout.

BROWSER SUPPORT
An example of this would be
MODERN FEATURES FOR using a vertical one-
MODERN BROWSERS dimensional layout for
small-screen devices, and
using a two-dimensional
layout for view on big screens,
Grid and flexbox were not 1 2 3 4 5 such as a desktop. Flexbox
1
always part of the CSS does not offer the ability to
specification, meaning that adapt for this requirement,
there is no support in older Item
whereas grid does.
browsers. All of the major Both flexbox and grid are
browsers have supported the 2 compatible with the content
full grid specification since ordering feature, so changing
2017. The main concern for from flexbox to grid should
Subitem
compatibility are Microsoft not be a significant problem if
browsers (IE and Edge), which it's required.
3
have high usage in businesses. Make sure that you keep
They introduced limited styling in a stylesheet
support in Internet Explorer separate from the main HTML
10, but full support has only content if you want to
been available since Edge 16. maximise maintainability.

feature _________________________________________________ 53
ESSENTIAL CREATE A QUICK BASIC GRID
Examples of using CSS Grid to create a series of simple layouts

PROPERTIES
THE PROPERTIES YOU NEED TO KNOW
FOR CREATING GRID-BASED LAYOUTS 1. HTML CONTENT
To start, link the external CSS file, e.g. <link
rel="stylesheet" type="text/css" href="1.css" />.
Everything CSS Grid goes in the <body>. Three
GRID-AUTO-FLOW sections are defined – one for each example
Enables you to define the flow grid. The data-grid attribute is used to provide
of grid cell layout using each section with a unique reference value that
horizontal 'column' or vertical can be used by the CSS. Each child element of
'row', making the grid act the grid will be become a cell of the grid.
similar to a table. <section data-grid="1"> 3
<div>1</div>
GRID-GAP <div>2</div> available space, so the middle column will be
Apply this to the grid <div>3</div> three times wider than the outer columns.
container to set spacing </section> [data-grid="1"] {
between each grid cell. The background: red;
default sets no spacing <section data-grid="2"> grid-template-columns: 1fr 3fr 1fr;
between cells. <div>1</div> }
<div>2</div> ---------------------------------------------------------------
GRID-COLUMN <div>3</div>
Sets the specific column to </section> 4. VERTICAL ROWS
place the grid cell. Use this to The second grid is set to display with a vertical
target specific cells via class, <section data-grid="3"> cell flow. As this is not the default flow for grid
ID or selector. <div>1</div> cells, the grid-auto-flow attribute is set to 'row'.
<div>2</div> The same approach is used to define the height
GRID-ROW <div>3</div> of each row, using the fr unit measurement.
Sets row location to place the <div>4</div> [data-grid="2"] {
grid cell. Use this to reference <div>5</div> background: green;
specific cells via class, ID or </section> grid-auto-flow: row;
selector. --------------------------------------------------------------- grid-template-rows: 1fr 3fr 1fr;
}
GRID-AREA 2. CSS GRID DEFINITION ---------------------------------------------------------------
Defines the grid area for a cell Create a file called '1.css'. This step sets
to cover using co-ordinates in formatting to be shared by all elements using 5. MIXED GRID
the format startX/startY/endX/ the 'data-grid' attribute. Display is set as grid to The final grid is presented with a layout allowing
endY or a cell reference name. make their first-level children act as the cells of for both vertical and horizontal content. Auto
the grid. Default background colour and text flow is set to 'column', setting the cells to flow
GRID-TEMPLATE-AREAS alignment for these grid cells are also set. horizontally. The first cell is set to span over two
A more advanced method for [data-grid]{ grid rows, guaranteeing the cells to flow
defining the grid layout using display: grid; horizontally over two rows.
grid-area reference names margin-top: 2em; [data-grid="3"] {
given to the created content padding: 1em; background: blue;
cells. grid-gap: 1em; grid-auto-flow: column;
} }
GRID-TEMPLATE-ROWS [data-grid="3"] > *:first-child{
Used to specify [data-grid] > * { grid-row: span 2;
measurements for individual background-color: #fff; }
rows within the design of the text-align: center;
grid layout. border: 1px solid #000;
}
GRID-TEMPLATE-COLUMNS ---------------------------------------------------------------
Similar to grid-template-rows,
but used to specify 3. HORIZONTAL COLUMNS
measurements for individual The columns template for grid 1 is set to contain
columns within the design of three cells. Measurements for the cells use the
the grid layout. fr unit to describe their width as a fraction of the
CSS Grid

GO TO THE NEXT LEVEL


An alternative approach to defining a grid layout by using reference names for content elements

1. DOCUMENT INITIATION menu header header header


4
First define the webpage as a HTML document
and link the external CSS stylesheet, e.g. <link
rel="stylesheet" type="text/css" href="2.css" />. menu content content side
Everything CSS Grid goes in the <body>.
---------------------------------------------------------------
menu content content side

2. GRID HTML
The grid must be defined in a way that will allow menu content content side
its container and child cells to be referenced by
CSS. This example uses semantic tags that have
a unique name for each content area, although menu footer footer footer
you could decide to use class names, data
attributes or IDs as an alternative.
<article> “menu footer footer footer”;
<section>Content</section> } MEASUREMENT
PROPERTIES
<header>Header</header> ---------------------------------------------------------------
<aside>Side</aside>
<footer>Footer</footer> 5. CONTAINER FORMATTING AND ATTRIBUTES
<nav>Menu</nav> With the grid layout now in place, the next step
</article> is to define additional presentation for the grid. The grid feature offers many ways to define
--------------------------------------------------------------- This step sets the grid container’s colours, along measurements for its cells, enabling you to
with the maximum width and minimum height. define both fixed and responsive layouts
3. CSS: REFERENCE NAMES Some padding is also added to enable the grid
Create a new file called '2.css'. This step to have a surrounding border space.
references each of the content elements inside article { FR
the article container and uses the grid-area max-width: 25em; The fr measurement unit specifies the
attribute to provide a unique reference name. min-height: 20em; width or height of a grid cell as a fraction of
This reference name will be used in the next step background-color: #333; the remaining space.
when defining the layout template for the grid. color: #444;
--------------------------------------------------------------- padding: 1em;
font-size: 150%; SPAN
article > aside { grid-area: side; } } Sets the width or height of a cell to cover
article > nav { grid-area: menu; } --------------------------------------------------------------- more than one cell space within the
article > section { grid-area: content; } defined grid template.
article > header { grid-area: header; } 6. CELL FORMATTING
article > footer { grid-area: footer; } The final step is to set the formatting of the grid
--------------------------------------------------------------- cells. This tutorial sets colours for the text and REPEAT
background, but you can add other CSS Used as shorthand to repeat the same
4. GRID SETUP presentation attributes to meet your width or height definition across multiple
The article in the HTML is used as the grid requirements. No new rules or limitations apply cells within the grid template.
container. The grid-template-areas attribute to grid cells, meaning you are still able to use
defines the layout of the grid using the grid-area your existing knowledge of CSS.
reference names identified in step 3. The setup article > *{ MINMAX
works like cells within a spreadsheet, where background: #fff; Allows you to define the minimum and
names that are vertically or horizontally adjacent color: #000; maximum height or width of a grid cell;
create one grid cell area. } useful for controlling responsive layouts.
article {
display: grid; header 6
grid-gap: .5em; PX / CM / MM / EM
grid-template-areas: Fixed unit measurements can be used in
“menu header header header” menu content side combination with fr, which results in
“menu content content side” fractional spaces being measured from the
“menu content content side” remaining space.
footer
“menu content content side”

feature _________________________________________________ 55
CSS Grid

WHAT ELSE DO I NEED TO KNOW? Six tips to get more from CSS Grid
1. LAYERING 5. CONTENT ORDERING
The z-index attribute can be applied to Grid allows you to order content independently
individual grid cells to allow them to be layered from the HTML definition, enabling you to
above or below other grid cells. optimise HTML for SEO while also providing
control for responsive design.

2. ALTERNATIVE LAYOUTS 5
Make use of CSS media queries to modify or 6. MAINTAINABILITY
redefine grid definitions for different screen sizes Use the grid flow attributes to allow future
or media types. adaptions of the HTML to automatically adapt 1 2
the grid without needing to update the CSS.
3 4

3. TEMPLATE ATTRIBUTES 1
Properties whose name begins with 'grid- header
template' are used to define the design of the overlay
grid layout. 1
content side
2

4. CELL ATTRIBUTES 3
footer 4
Properties that don’t start with 'grid-template'
6
are used to place cells within the grid. 5

WHAT ABOUT TEMPLATE VS CONTENT The two parts of the grid


ACCESSIBILITY? Grids consist of two parts – templates and management. Once a template has been
content. This enables reusable grid layouts that defined, you are able to apply it to a container
can be called from HTML markup using tag element that stores content elements. Content
The same ability of grids to re-order content
names or attributes such as class or ID values. flow within the grid appears in accordance to the
for responsive purposes can also be applied
As well as being a benefit for responsive layouts, settings of the grid template, which allows for
to increase accessibility. Whether it’s
this reusability has many advantages for agile custom rules to be applied directly to individual
changing or extending the stylesheet, or,
workflow strategies involving change content elements.
with the help of JavaScript, users can be
given options to choose the order that best
suits what they need. Template
In its simplest form, this can be achieved
Head
by attaching additional stylesheets to load,
possibly as a result of settings stored in a Intro
cookie, local storage or on the server. More
advanced accessibility control can be Side Main
executed as a result of interactions with a
HTML form that triggers JavaScript to adapt Footer
the grid ordering.

1 2 3 4 5
Page 1 Page 2
Content Head Content Head

Intro Content Intro Content


2 1 5 4 3
Content Content
Side Main Content Side Main Content

Footer Content Footer Content

56__________________________________________________feature
CSS Grid

subgrid nested grid


title title

a1 a1
main
main
aside2 aside2

aside3 footer aside3


footer

GRID FOR AGILITY


Use CSS grid as a tool for agile project development

The ability of grid to keep layout against unexpected changes that by providing full control to the using nested grid, it is the feature’s
definition entirely independent from could otherwise escalate to derail designers for defining the layout ability to adapt parent grids without
the HTML content is not only good your schedule and budget without concern for the HTML. concern for their content that will
for responsive design and SEO but planning. An example of this would Future additions to the grid benefit your ability to be agile by
also for project management. A lot be a change request to alter the feature will allow advanced layouts eliminating risk and reducing
of talk exists about agile position of content, which would to be defined with lower complexity. testing requirements. In addition,
development being a project traditionally require you to modify One example of this is the proposed the automatic management of
management methodology, but it’s both the CSS and HTML. This can subgrid feature, which will enable subgrids by the browser will help to
as much about how you implement be problematic for large projects cells to act as a subgrid that keep formatting simple and
your design and its code. where design and content are automatically inherits the required consistent across all developers,
By using CSS grid effectively, you responsibilities of separate people cell layout from its parent. While providing better ability to adapt
are able to protect your project or teams. Grid resolves this issue subgrid layout is already possible your CSS whenever required.

RESOURCES
W3C SPECIFICATION GRID POLYFILL GRID LAYOUT EXAMPLES
w3.org/TR/css-grid-2 smashingmagazine.com/2018/07/ github.com/FremyCompany/ gridbyexample.com/examples
The latest details of the CSS grid css-grid-2 css-grid-polyfill A selection of pre-made grid
specification. Includes details Learn about the proposed subgrid One of several polyfills available layouts that you can use to
about proposed features, such as feature in more detail, complete to bridge compatibility with older kickstart your web design or
subgrid that will be implemented with full examples for using the browsers. Make sure to take a look content section layout. Examples
by future browser releases. proposed specification. at the full description of its include both simple and advanced
capabilities and limitations. layout designs.

feature _________________________________________________ 57
Tutorials

Make your websites


run faster with
optimised CSS
While performance optimisations in JavaScript code are well-known,
CSS is an often-overlooked part of the speed game

58__________________________________________________tutorial
Tutorials

C
SS must pass through a relatively entire website after replacing your CSS files with the </style>
complex pipeline, just like HTML and minified ones – one never knows what mistakes the </head>
JavaScript. The browser must download optimiser caused. <body>
the files from the server and then proceed <div class="blue">
to parsing and applying them to the DOM. Due to 5. Inline critical CSS Hello, world!
extreme levels of optimisation, this process is usually Loading external stylesheets costs time due to latency </div>
pretty fast – for smaller web projects not based on – anyone remember the ‘flash of unstyled content’? The
frameworks, CSS usually makes up just a small part of most critical bits of code can therefore go into the header 6. Permit antiparallel parsing
total resource consumption. tag. Make sure not to overdo it, however. Keep in mind @import adds structure to your CSS code. Sadly, the
Frameworks upset this equilibrium. Include a that the code must also be read by humans performing benefits are not for free: as imports can nest, parsing
JavaScript GUI stack like jQuery UI, and watch CSS, JS and maintenance tasks. them in parallel is not possible. A more parallelisable
HTML sizes skyrocket. Often, developers usually feel the <html> way uses a series of <link> tags, which the browser can
pinch last – when seated behind a powerful eight-core <head> fetch at once.
workstation with T3 internet, no one cares about speed. <style> @import url("a.css");
This changes as latencies or CPU-constrained devices .blue{color:blue;} @import url("b.css");
come to play.
Optimising CSS requires a multi-dimensional approach.
While hand-written code can be slimmed down using
various techniques, going over framework code by hand
is inefficient. In these cases, using an automated
minimiser yields better results – developer time is not an
unlimited resource.
The following steps will take us on a journey through
the world of CSS optimisation. Not every single one might
be directly applicable to your project, but do keep them
in mind.

1. Use shorthand
The fastest CSS clause is one that never gets parsed.
Using shorthand clauses, such as the margin declaration
shown below, radically reduces the size of your CSS files.
A lot of additional shorthand forms can be found by
googling ‘CSS Shorthand’.
p { margin-top: 1px;
margin-right: 2px;
margin-bottom: 3px;
margin-left: 4px; }
1
p { margin: 1px 2px 3px 4px; }

2. Find and remove unused CSS


Eliminating unneeded parts of your mark-up obviously
causes immense speed gains. Google’s Chrome browser
has this functionality out of the box. Simply go to
View>Developer>Developer Tools and open the Sources
tab in a recent version, and open the Command Menu.
After that, select Show Coverage and feast your eyes on
the coverage analysis window highlighting unused code
on the current webpage.

3. Do it in a more
comfortable fashion
Navigating through the line-by-line analysis is not
necessarily comfortable. Chrome’s Web Performance
Audit returns similar information – simply open it from
the toolbar, View>Developer>Developer Tools>Audits
and let it run. When done, a list of problematic elements
will pop up.

4. Be aware of the problems


Keep in mind that an automatised analysis of a CSS can 2
always lead to errors. Perform a thorough test of the

tutorial _________________________________________________ 59
Tutorials
Make your websites run faster with optimised CSS

@import url("c.css"); target { background-color: #ffffff; } 11. Use a texture atlas


v<link rel="stylesheet" href="a.css"> target { background: #fff; } Loading multiple small sprites is inefficient due to protocol
<link rel="stylesheet" href="b.css"> overheads. CSS sprites combine a series of small pictures
<link rel="stylesheet" href="c.css"> 9. Eliminate unneeded into one big PNG file, which is then broken apart via CSS
zeros and units rules. Programs such as TexturePacker simplify the
7. Replace images with CSS CSS supports a wide variety of units and number creation process greatly.
Years ago, a set of semi-transparent PNGs to create formats. They are a thankful target for optimisation – .download {
translucent effects on websites was commonplace. both trailing and following zeros can be removed, as is width:80px;
Nowadays, CSS filters provide a resource-saving demonstrated in the snippet below. Furthermore, height:31px;
alternative. As an example, the snippet accompanying this keep in mind that a zero always is a zero, and that background-position: -160px -160px
step ensures that the picture in question appears as a adding a dimension does not add value to the }
grayscale version of itself. information contained. .download:hover {
img { padding: 0.2em; width:80px;
-webkit-filter: grayscale(100%); /* old margin: 20.0em; height:32px;
safari */ avalue: 0px; background-position: -80px -160px
filter: grayscale(100%); padding: .2em; }
} margin: 20em;
avalue: 0; 12. Chase down the px
8. Use colour shortcuts One neat way to increase performance uses a specialty of
Common wisdom teaches that six-digit colour descriptors 10. Eliminate excessive the CSS standard. Numeric values without a unit are
are the most efficient way to express colours. This is not semicolons assumed to be pixels – removing the px saves two bytes for
the case – in some cases, shorthand descriptions or This optimisation is somewhat critical, as it affects each number.
colour names can be shorter. changes of code. CSS’s specification lets you omit the h2 {padding:0px; margin:0px;}
last semicolon in a property group. As the savings h2 {padding:0; margin:0}
achieved by this optimisation method are minimal, we
Don’t interfere mention this mainly for those who are working on an 13. Avoid expensive properties
with CDNs
While minifying stock CSS looks tempting, keep the
automated optimiser.
p {
Analysis has shown some tags to be more expensive than
others. The list accompanying this step is considered to
costs in mind. A big file served from a fast CDN can . . . be especially performance-hungry – avoid them when
be faster than a small file served from a slow server. font-size: 1.33em given the opportunity to do so.
} border-radius

Not every hex code can be shortened. Typically code has to be in pairs to work

60 _________________________________________________tutorial
Tutorials
Make your websites run faster with optimised CSS

Simplify
debugging
Finding errors in minified or
optimised CSS is tedious and
should be avoided at all costs.
The safest workaround involves
using the unoptimised CSS files
during debugging, generating
an optimised version only as
the website is pushed live.
Should this be unworkable for
some reason, limit yourself to
auto-generated optimisations.
Many if not most optimisers
produce so-called MAP files
during execution. These can then
be loaded into your debugger
– when done, the debugger can
correlate the optimised code to
the unoptimised files found at
another location in the file system.

11 box-shadow
transform
filter
:nth-child
position: fixed;
etc.

14. Remove whitespace


Whitespace – think tabs, carriage returns and spaces –
makes code easier to read but serves little purpose from
a parser’s point of view. Eliminate them before shipping.
An even better way involves delegating this job to a shell
script or similar appliance.

15. Eliminate comments


Comments also serve no purpose to the compiler. Create
a custom parser to remove them before delivery. Not only
does that save bandwidth but it also ensures that
attackers and cloners have a harder time understanding
the thinking behind the code at hand.

16. Use automatic compression


Yahoo’s user experience team created an application
that handles many compression tasks. It ships as a JAR
file, available at yui.github.io/yuicompressor, and can
be run with a JVM of choice.
java -jar yuicompressor-x.y.z.jar
Usage: java -jar yuicompressor-x.y.z.jar
[options] [input file]
Global Options
-h, --help Displays this
information
--type <js|css> Specifies the
type of the input file

Don’t go crazy
Premature optimisation is a dangerous game.
While attempting to squeeze out the last bit of
performance from your CSS is intellectually
challenging, check if lower-hanging fruit are
available before committing your time.

tutorial _________________________________________________ 61
Tutorials
Make your websites run faster with optimised CSS

16
Essential resources
----------------------------------------------------
On the problems of
automated CSS analysis
css-tricks.com/heres-the-thing-about-unused-css-tools

Automatically removing unused parts from stylesheets


is not a computationally trivial task. Those interested in
algorithmics will find this discussion highly interesting.

17. Run it from NPM 19. Set up caching


Should you prefer to integrate the product into Node.JS, An old adage claims that the fastest file is one that never
visit npmjs.com/package/yuicompressor. The badly gets sent across the wires. Making the browser cache ----------------------------------------------------
maintained repository contains a set of wrapper files and requests achieves this efficiently. Sadly, the setup of the CSS selector benchmark
a JavaScript API. caching headers must take place on the server. Make good sitepoint.com/optimizing-css-id-selectors-and-other-myths
var compressor = require('yuicompressor'); use of the two tools shown in the screenshots – they
Browsers keep getting faster and faster. This survey
compressor.compress('/path/to/ provide a swift way to analyse the results of your changes.
performed by SitePoint cleans up a few old rumours about
file or String of JS', { CSS selector length and the impact on performance.
//Compressor Options: 20. Bust the cache
charset: 'utf8', Designers often dislike caching due to fear of problems ----------------------------------------------------
type: 'js', with upcoming changes. A neat way around the problem PageSpeed Insights
involves including tags with the file name. Sadly, the developers.google.com/speed/pagespeed/insights
18. Keep Sass et al in check scheme outlined in the code accompanying this step
Google’s PageSpeed Insights tool runs predefined checks on
While CSS selector performance is not nearly as critical as does not work everywhere as some proxies refuse to
your webpage and tells you areas worthy of improvement.
it was some years ago (see resource), frameworks such cache files with ‘dynamic’ paths.
as Sass sometimes emit extremely complex code. Take a <link rel="stylesheet" href="style.
look at the output files from time to time and think about css?v=1.2.3">
ways to optimise the results.
21. Don’t forget the basics
Optimising CSS is just part of the game. If your server
does not use HTTP/2 and gzip compression, a lot of time
is lost during data transmission. Fortunately, fixing these
two problems is usually simple. Our example shows a few
tweaks to the commonly used Apache server. Should you
find yourself on a different system, simply consult the
server documentation.
pico /etc/httpd/conf/httpd.conf
AddOutputFilterByType DEFLATE text/html ----------------------------------------------------
19
AddOutputFilterByType DEFLATE text/css Cache-busting techniques
css-tricks.com/strategies-for-cache-busting-css
19
Our discussion of ways to force cached resources to update is
limited. This tutorial provides additional hints.

----------------------------------------------------
All about HTTP/2
developers.google.com/web/fundamentals/performance/
http2

Google’s developer portal contains an excellent introduction


into all things related to HTTP/2.

----------------------------------------------------

62__________________________________________________tutorial
31
O EC
D
FF E
The perfect

ER MB
EN
S
*
gift from just $23

8
FROM $23 EVERY 3 MONTHS ($93 PER 13 ISSUES YEARLY)

www.myfavouritemagazines.co.uk/pin/xmas187
ORDER HOTLINE: ‫גגڷ‬٨‫׎‬٩‫אדזאזגזגגב‬
PLEASE QUOTE XMAS187 WHEN ORDERING BY PHONE
nXz0³«0 ¨0zx z(ç‫ٳ‬I«X(ç‫ז‬xÁ ‫¨ו‬xz(³ÁÈ«(ç‫׎׏‬xÁ ‫¨א‬x٨JxÁ٩
*Terms and conditions: Savings calculated against the full RRP (single issue price x frequency). Dollar prices quoted are for the United States, other global territory dollar pricing may vary.
ÁǝǣɀȒǔǔƺȸǣɀǔȒȸȇƺɯɀɖƫɀƬȸǣƫƺȸɀȒȇǼɵِçȒɖƬƏȇɯȸǣɎƺɎȒɖɀȒȸƬƏǼǼɖɀɎȒƬƏȇƬƺǼɵȒɖȸɀɖƫɀƬȸǣȵɎǣȒȇɯǣɎǝǣȇ‫ג׏‬ƳƏɵɀȒǔȵɖȸƬǝƏɀƺِçȒɖȸɀɖƫɀƬȸǣȵɎǣȒȇǣɀǔȒȸɎǝƺȅǣȇǣȅɖȅɀȵƺƬǣˡƺƳƏȇƳɯǣǼǼƺɴȵǣȸƺƏɎɎǝƺ
end of the current term. Payment is non-refundable after the 14 day cancellation period unless exceptional circumstances apply. Your statutory rights are not affected. Prices correct at point
of print and subject to change. Full details of the Direct Debit guarantee are available on request. For full term and conditions please visit: bit.ly/magtandc. Offer ends 31st December 2018
Tutorials

Style a site
using Sass
Sass is a style sheet language that extends CSS. It’s common to
take advantage of a CSS ‘preprocessor’ like Sass to make styling
easier, and in this tutorial we’ll show you how

DOWNLOAD TUTORIAL FILES


________________________________________________ www.filesilo.co.uk/webdesigner
Tutorials

Y
ou can do a lot with CSS – perhaps more 3. Command line compilation 6. The main stylesheet
than you might think – but the Now we can run the Sass compiler at the command We’re using styles.css as our main CSS entry point, which
venerable style sheet language has its line to convert our .scss file into CSS output. You’ll later on we’ll use to import other modules. This means we
limitations. In a modern web project, with notice in the output file that the variables are gone and need to tell Sass to generate this file, so we also need to
npm modules, JavaScript frameworks, ES6 and more, it we’re just left with standard CSS syntax that is usable create a styles.scss file in our src/sass folder. If you’re running
can feel somewhat anachronistic to fall back to writing by the browser. “sass --watch” as before, this will automatically be compiled
vanilla CSS. sass sass-input.scss css-output.css into CSS in the ‘public/css’ folder, and refreshing your site will
Fortunately, there are options out there that allow you show its changes. Try making some modifications and
to use other languages that compile to CSS. Referred to 4. Automating build refreshing the HTML page in the browser as you go.
as ‘preprocessors’, these tools integrate into your web This is great, but you don’t want to run the Sass // styles.scss
build process and generate usable style sheets from compiler manually every time you make changes. One body {
whatever extension language you’ve chosen. option is to have it listen for changes to files in a font-family: sans-serif;
Sass (Syntactically Awesome Style Sheets) is one of the directory and automatically recompile the output to a text-align: center;
most popular of these options. Sass adds many valuable different directory (preserving filenames). This also }
new language features that aren’t (currently) available in effectively lets you segregate your source .scss file from
CSS to help make your sites and apps more maintainable. your built CSS. 7. Colour scheme
These include things like ‘mixins’ and ‘control directives’, mkdir src Let’s look at how Sass can help us manage a colour
which sound daunting but are actually quite mkdir src/sass scheme for the site. It’s common to have a palette of 5 or
straightforward, and we’ll look at these in this tutorial. mkdir public 6 colours for a webpage. We can externalise these in
There are actually two different syntaxes for Sass, one mkdir public/css ‘_colours.scss’. The underscore prefix tells Sass not to
that uses a ‘.scss’ file extension, and one that uses ‘.sass’. sass --watch src/sass/:public/css/ compile this into a new HTML file (a ‘partial’). But we can
The former looks more like CSS (in fact, all .css files are use it in a slightly different way.
valid .scss files), while the latter eliminates CSS’s brackets 5. A starter site // _colours.scss
and semicolons in favour of indentation and newlines. Now let’s look at a simple starter site, which we can $colour-primary: #231651;
We’ll focus on .scss, but the choice is simply down to use to play around with Sass styling. We can get $colour-secondary: #2374AB;
personal preference. started by cloning an unstyled example site. The key $colour-light: #D6FFF6;
thing to note is that our HTML page knows nothing $colour-highlight1: #4DCCBD;
1. The compiler about Sass. It has a single CSS file entry point, which $colour-highlight2: #FF8484;
Using Sass essentially requires a compiler. The simplest we’ll create next.
way to do this would be at the command line. You can cd public
do so using Homebrew. The Sass compiler is curl -o index.html https://raw.
implemented in several different languages, and githubusercontent.com/simon-a-j/sass-
Homebrew will install the Dart version, which is fast. tutorial/
brew install sass/sass/sass master/public/index.html

2. Our first Sass file


5 8
Let’s try creating a simple Sass file to see the compiler in
action. One of the simplest concepts in Sass is variables, Our site now has a colour scheme thanks to a Sass partial
which can be specified once with a ‘$’ prefix and then
used throughout your code. We’ll create ‘sass-input.scss’. 8. Using variables
$text-color: #cccccc; To use these colour variables we’ve just set up, we can tell
body { Sass to import the content of ‘_colours.scss’ into our main
color: $text-color; style sheet. We do this using an @import statement.
Here’s the starter project we’ll use to
} experiment with Sass styling Once you’ve done this, notice how the variables are
resolved within the output CSS file.
1 // styles.scss
@import “_colours.scss”;
body {
font-family: sans-serif;
text-align: center;
background: linear-gradient(155deg,

Build pipeline
We’ve looked at the simplest possible command-
line usage of Sass, but in many real-world
scenarios, you’ll want it more neatly integrated
into your build pipeline. A lot of popular
framework starter kits do this already, but you can
also set it up yourself with, say, Node – in which
case you can use gulp or npm scripts and the
node-sass module.
The official Sass website, which has many useful resources and comprehensive documentation

tutorial _________________________________________________65
Tutorials
Style a site using Sass

10 11

A mixin helps us maintain backward compatibility with older


We can introduce a responsive grid, which is easier to manage with Sass variables and nesting browsers when we use CSS transforms like rotation

$colour-primary 70%, $colour-secondary 10. Responsive grid -moz-transform: $value;


70%); Now let’s arrange our content into a responsive grid -ms-transform: $value;
color: $colour-light; format. Sass has a couple of features to make this transform: $value;
min-height: 100vh; significantly easier to manage. As well as using variables }
} to specify our breakpoints, we can nest @media queries .profile-logo {
h1 { within other styles, which makes behaviour specific to font-size: 60px;
color: $colour-highlight1; screen size much more readable. font-family: cursive;
} $breakpoint: 800px; @include transform(rotate(25deg));
h2 { .profile-body { }
color: $colour-highlight2; display: flex;
} align-items: stretch; 12. Mixins and variables
justify-content: space-around; We can also use a mixin with multiple parameters,
9. Nesting styles margin-top: 32px; combined with some variables that we define, to more
Another useful feature of Sass is the ability to nest margin-left: 10vw; elegantly handle styling of various parts of the page. If we
styles. That is, you can specify a style for an element margin-right: 10vw; create a mixin that defines foreground and background
that is only applied if that element occurs within a @media screen and (max-width: colour, this will enable us to select appearances for
parent element. Let’s use this to differentiate our styling $breakpoint) { different sections from a finite list of style variables.
of links depending on whether they appear in the flex-direction: column; $style1: (foreground: $colour-light,
header or body. } background: $colour-secondary);
a { } $style2: (foreground: $colour-primary,
color: $colour-secondary; .profile-section { background: $colour-highlight1);
} background-color: $colour-highlight1; $style3: (foreground: $colour-primary,
.profile-header { color: $colour-primary; background: $colour-highlight2);
a { margin: 16px; @mixin content-style($foreground,
font-size: 16px; border-radius: 10px; $background) {
margin-left: 10px; width: 340px; color: $foreground;
margin-right: 10px; .profile-content { background-color: $background;
padding: 10px; padding: 20px; }
border-radius: 5px; }
color: $colour-light; @media screen and (max-width: 13. Using our new mixin
background-color: $colour-secondary; $breakpoint) { Now, we can use the content-style mixin to replace colour
} width: 100%; and background-colour statements elsewhere in our style
} } sheet. When including it, we specify one of the two $style
} variables as a parameter. Note the ... after the variable
name, which tells Sass to pass the variable’s content as a
11. Introducing mixins list, matching the number of parameters the mixin expects.
Mixins and Mixins are another powerful Sass feature, which you can .profile-header {
placeholders think of as a way of defining reusable stylesheet functions.
A mixin is defined once, can take parameters, and can then
a {
@include content-style($style1...);
These might look quite similar, and there are many
scenarios where you could use either. Generally be invoked anywhere in your Sass code. One use case for // …
mixins are most appropriate where you have this is to handle vendor prefixing. If we want a CSS }
parameters that will vary depending on where transform to work in older browsers, this might require a }
they are used. If the style snipped is always going
‘-webkit’ prefix for Chrome and Safari, for example. Let’s .profile-section {
to behave exactly the same way, with no variables
define a mixin that takes care of this for us. @include content-style($style2...);
passed to it to affect its behaviour, then a
placeholder would make more sense. @mixin transform($value) { // …
-webkit-transform: $value; }

66 _________________________________________________tutorial
Tutorials
Style a site using Sass

Other preprocessors
Sass is just one of the CSS preprocessors out there,
and you might want to consider checking out the
competition. Preprocessing is largely a stylistic
preference, and the best choice is really the one that
you find best suits your personal development style (or
integrates most easily with other tooling you use).
Less (Leaner Style Sheets) is, like Sass, an extension
of CSS that maintains backward compatibility. It’s
written in JavaScript so requires Node.
Stylus has flexible syntax support, letting you write
either regular CSS, .sass style CSS, or omit braces,
semicolons and colons completely and write very
concise style sheets.
PostCSS takes a slightly different approach to the
competition, allowing you to pick and choose which
language extensions you need via a plugin system,
rather than shipping everything at once.
The features supported by most of the preprocessing
solutions are fairly similar – you’ll generally get
variables, nesting, mixins, functions and imports.

14. Inheritance 75%); 20. Output formatting


Another very powerful feature of Sass is inheritance. Right $colour-highlight1: Let’s finish up by looking at the output Sass generates. If
now we have two different styles for links in our page. If lighten(complement($colour-primary), 50%); you’ve been tracking your CSS files as we’ve made
we want to use common styles across both, rather than $colour-highlight2: changes, you’ll notice they remain quite readable.
copying and pasting CSS, why don’t we use a placeholder lighten(complement($colour-secondary), 50%); However, you can also have Sass build condensed CSS,
class, denoted with ‘%’, which can be extended by both, which is less human-readable but still ready to ship. You
allowing them to inherit its styles? 17. Selecting a new set of can do this using the ‘--style’ command-line flag.
%link-shared { colours
font-size: 16px; Now, we can modify the entire colour scheme for the sass src/sass/:public/css/ --style
margin-left: 10px; site simply by specifying a new colour-primary value in compressed
margin-right: 10px; the ‘_colours.scss’ file. Give it a try by experimenting with
padding: 10px; alternative colours. We could also have Sass randomise 21. More Sass
border-radius: 10px; it (but remember this refers to the point at which your We’ve now explored quite a few features of Sass, and our
} site is built, not runtime). You can also try adjusting the site isn’t looking too bad. Hopefully you’re beginning to see
logic we’re using to derive the other colours in the how Sass helps us develop more maintainable style sheets.
15. Extending classes theme from the primary. We haven’t covered every feature of the language – there
Now we can extend the link-shared class to define link $red: random(255); are many more useful functions shipped with it, and
styling throughout our site. This is starting to look quite $green: random(255); advanced features like control directives (such as @if, @for
elegant. We define what a link generally looks like just $blue: random(255); and @while) that are often used to create complex library
once, reuse it throughout, and specify colours from the $colour-primary: rgb($red, $green, $blue); functions. Overall, remember that Sass is entirely a stylistic
palette for each link using a mixin. preference. You can do everything we’ve seen with pure
.profile-header { 18. Using libraries CSS if you like, but you should definitely think about
a { Sass’s module system also makes it very straightforward preprocessing as your work becomes more complex.
@extend %link-shared; to use 3rd-party libraries with minimal effort, and without
@include content-style($style1...); shipping large runtime files to your end users. Let’s try out 13
} the Angled Edges library, which we can use to create
} sloped edges for objects on our page.
a { git clone https://github.com/josephfusco/
@extend %link-shared; angled-edges.git src/sass/angled-edges
@include content-style($style3...);
} 19. The Angled Edges mixin
We can import Angled Edges the same way we did for our
16. Modifying the theme colour scheme partial. It’s then usable via a mixin that ships
Now let’s take a look at how easy Sass makes it to modify with the library. Let’s try it out in our profile-section class.
the theme of our site. The current colours might not be @import “angled-edges/_angled-edges.scss”;
perfect. We cannot only modify the colour variables, but .profile-section {
we can also use some Sass functions to procedurally @include angled-edge(“outside bottom”,
generate colours that match a primary of our choosing. “lower right”, $colour-highlight1);
// _colours.scss @include angled-edge(“outside top”,
$colour-primary: #2E1F27; “upper right”, $colour-highlight1);
$colour-secondary: lighten($colour-primary, margin: 120px 16px 120px 16px;
25%); // ...
$colour-light: lighten($colour-primary, }

tutorial _________________________________________________ 67
with Cassidy Williams
LET’S BREAK DOWN HOW TO MAKE ART WITH CSS BY MAKING A CUTE ICE
CREAM BAR GRAPHIC, GOING THROUGH TECHNIQUES STEP BY STEP

68 _________________________________________________feature
CSS Art

SAY HELLO TO CSS ART


Making CSS art can be intimidating, but it's easy
once you break graphics down into simple parts

If you peruse websites like (and problems in general)


CodePen, DevArt and Dribbble, it’s modularly and improves your
very easy to feel overwhelmed by speed when writing CSS. It’s also a
the incredible things that great way for designers and
developers and designers make, developers to get on the same
especially when you’re just page when working on a user
starting out. I made my first piece interface together. As you practise
of CSS art after lurking on these and refine your skills making CSS
sites for years and eventually art, you’ll see an improvement in
mustered up the courage to try your day-to-day work (and you
and do it. Now, a few years and might even enjoy it more, too).
over 100 experiments later, it’s In this article, we’re going to be
one of my favourite hobbies. making this cute ice cream bar
Making CSS art is interesting graphic in CSS. I’ll talk through and
and fun. It teaches you nuances of give you the code to follow, so that
CSS that you might not normally you can customise it and make it
work with, helps you see graphics your own. Let’s get started!

As you practise and refine your skills


making CSS art, you’ll see an
improvement in your day-to-day work
(and you might even enjoy it more, too)

WHERE CAN
I FIND…?
Want to make
graphics after this
article and not sure
where to start?
Check out Dribbble,
Behance and
CodePen Challenges
for inspiration. If you
end up using one of
the graphics or ideas
you find on those
sites, don’t forget to
credit the work!

feature _________________________________________________69
CSS Art

LET'S MAKE ART WITH CSS


A step-by-step guide to creating an ice cream bar graphic

1. SETTING UP YOUR 2. COLOURS AND SIZES 3. POSITIONING align-items: center;


DOCUMENT Normally when you have a graphic AND TRANSFORMING justify-content: space-between;
Before we write any CSS, we have in front of you to make, you will Right now, our image is all blocky height: 58px;
to actually have something to need the dimensions and colours and in the corner. Before we shape }
style. You can use a preprocessor of that graphic. In this particular everything better, let’s add some
like HAML or Pug, or just straight case, I’ll be providing you with positioning and transforms. .eyes {
HTML. I’ll stick with pure HTML those dimensions and colours. Personally, my favourite display: flex;
and CSS in our examples, but When you don’t have me around positioning techniques (generally) justify-content: space-between;
you’re free to use what you’re though, I recommend getting are absolute positioning width: 145px;
most comfortable with. Pull up a yourself a colour picker tool (I containers, and using flexbox for }
blank Pen on CodePen or an HTML personally use Digital Color Meter everything else. If you prefer using ---------------------------------------------
document, and include the on Mac and ColorPic on Windows), absolute and relative positioning
following for the ice cream bar in and a screenshot tool to figure out for everything, or even CSS Grid, 4. PSEUDO-ELEMENTS
the <body>. your dimensions (the native ones go for it! Now, we have to position Our little ice cream bar is looking
for your operating systems work the container in the middle of the pretty good, if I do say so myself!
<div class=’container’> just fine). Let’s add those page (I’ll be using absolute One last concept that is incredibly
<div class=’ice-cream’> dimensions and colours now to positioning and a translate helpful for making CSS art is
<div class=’glare’></div> our document. transform), and make sure the pseudo-elements. Every single
<div class=’face’> contents of the main container are element on a page can actually be
<div class=’eyes’> body { centred and rotated as needed. three elements: the main element,
<div class=’eye left’> background: #FED550; You might notice that I also added ::before, and ::after. You can style
</div> } a couple of dimensions for the ::before and ::after as if they’re
<div class=’eye right’> .'face' and '.eyes' classes – that’s for separate <div>s within any
</div> .ice-cream { handling the spacing within that element. For example, I could have
</div> width: 240px; container. Go ahead and add these changed the .eyes container to
<div class=’mouth’></div> height: 350px; changes in yourself to each class: have no .eye <div>s at all, and just
</div> background: #F982BF; style a ::before and ::after for each
</div> } .container { eye. That would have been cool,
<div class=’stick’></div> position: absolute; but that would make styling the
</div> .glare { top: 50%; glare on each eye impossible. That
--------------------------------------------- width: 35px; left: 50%; being said, for the final missing
height: 70px; transform: translate(-50%, glare on those eyes, let’s add a
background: #FF98CC; -50%); ::before pseudo-element to make
} display: flex; that possible. The key things to
flex-direction: column; add to a pseudo-element are a
.eye { align-items: center; display value and content: ‘’. Check
width: 18px; } it out, and with that, we’re done!
height: 18px;
background: #FF2995; .ice-cream { .eye {
} display: flex; position: relative;
flex-direction: column; }
.mouth { justify-content: space-around;
width: 75px; } .eye::before {
height: 25px; display: block;
background: #FF2995; .glare { content: ‘’;
} position: relative; position: absolute;
left: 170px; top: 20%;
.stick { bottom: 20px; left: 50%;
width: 60px; transform: rotate(-38deg); transform: translateX(-50%);
height: 72px; } width: 5px;
background: #ECAA7D; height: 5px;
border-top: 12px solid #DB9E74; .face { background: #fff;
} display: flex; border-radius: 100%;
--------------------------------------------- flex-direction: column; }

70 _________________________________________________feature
CSS Art

Q&A WITH CASSIDY


Cassidy Williams tells us how she started
making art with CSS and what inspired her

Hi Cassidy. Tell us a little about yourself and how CSS


is part of your life.
Hi there! I’m Cassidy and I’m a senior software engineer
at CodePen. CSS is one of the first things I taught myself
how to code back when I was in middle school and first
'discovering' the ability to make things and put it on the
internet (from my own personal sites to guild pages on
Neopets). Obviously the internet is very different now, but
CSS is still around and better than ever! I love
experimenting with it and seeing new features come out.

What inspired you to try out creating art with CSS?


I first got interested in making CSS art (with CodePen,
actually) when I saw that Google launched their DevArt
website (devrt.withgoogle.com) back in 2014. After
experimenting with it a little on my own and following
developers I admire, I decided to make it a goal to make
CSS art regularly, around once a week, and eventually I was
making it so often it led to me being introduced to the
team at CodePen, and now I work there!

What advice would you give to anyone wanting to get


into the industry or those looking to progress?
It’s cliché because it’s true: Practise, practise, practise!
Doing CSS art and experiments has made me a better
developer. It forces you to think modularly and improves
your ability to write UIs quickly. If you want to get better,
keep building, even if it means trying to copy someone
else’s art (don’t forget to give credit) or making
something that might seem completely useless. Also, as
someone new to the industry, it’s a really interesting skill
to have in your portfolio. Even though you might not use
CSS art to actually get a job, it’s a great way to get a foot
in the door and show off your logical, creative code.

YOU’RE AN ARTIST!
We made something really fun
together today. If you’d like to check
out my final result, you can find it on
my CodePen profile (codepen.io/
cassidoo/pen/QJmxWX). Making
CSS art is really just a matter of
applying the concepts we talked
about in interesting and fun ways.
You can take these techniques and
run with them, and even add your
own animations with keyframes and
transitions. All this being said, I hope
you learned something new, and
this motivated you to try your hand
at making something beautiful.

feature __________________________________________________71
r ones and how
hodology

ion of many, can save


ime, leading to more
scale and maintain

t Potato

__________________________________________________
CSS METHODOLOGIES

SS methodologies refer to sets

C writing modular, reusable and


Although CSS is an easy langu
without an agreed-upon convention t
almost as fast as it is written. Since ea
is defined on its own line, files get hu
them a nightmare to maintain. Prepro
Sass, Less and Compass, have done
this problem by allowing selectors to
blocks of code to be replaced with si
declarations. While this helps, large pr
require thousands of lines of code. Fo
preprocessors also allow CSS to be s
files, or ‘partials’. But what to include i
how they are named must be agreed
otherwise their use can do more har

MANAGE SPECIFICITY
Another potential problem experience
projects is managing specificity. CSS as
each style rule, so when multiple rules
same element, the highest weighted ru
more specific and is therefore applied.
equal-weight rules are used the lowest
is calculated using four number groups
0-0-0-0, where numbers do not overf
to another, so 0-12-21-5 is valid. Each ele
element in a selector increments the ri
‘h1’ is 0-0-0-1 and ‘div::before’ is 0-0-0
attribute or pseudo-class increments t
‘.some-class.another-class’ is 0-0-2-0 a
some-class .another-class:hover’ is 0-0
the next group, e.g. ‘#some-id#anothe
‘ul#some-id img.some-class:active’ is 0
applied using HTML style attributes inc
group and are therefore the most speci
higher the overall number, the more sp
So if one developer uses ‘div.some-clas
an element, it is not possible to overrid
the code using ‘.some-class’ on its ow
common practice to use only single-cla
possible.
To solve these and other CSS imple
groups of coders around the world h
different CSS methodologies, or sets
practices, each with their own focuse
disadvantages. They are not framew
rather rules for writing CSS code that encourage
developers to stick to conventions that make code easier
to write and maintain, saving hours of development time.
These methodologies are not mutually exclusive and can
be used together in a way that best suits developers.
In this article we will take a look at a few of the most
popular CSS methodologies, highlighting their pros and Methodologies
cons, and how they can be combined together in a provide rules for
writing CSS code
custom methodology.

feature _________________________________________________ 73
CSS METHODOLOGIES

Popular CSS methodologies Of the vast number of CSS methodologies, we will explore the
most popular, discussing their advantages and disadvantages

and also the lack of consistency


that is caused by the inability to
share CSS between objects.

4. SCALABLE AND MODULAR


ARCHITECTURE FOR CSS (SMACSS)
Split CSS code across multiple
files for better performance
and organisation

SMACSS works by dividing CSS


into five categories – base, layout,
module, state and theme –
commonly split into separate files.
Base styles override the default
styles and are mainly applied using
element selectors:
h1 { font-size: 20px; }
a { text-decoration: none; }

Layout styles are for major objects


like headers and sidebars. They
are applied using IDs or classes
with generic helper declarations
optionally prefixed with ‘l-’:
#header { height: 50px; }
.l-right { float: right; }

Module styles are for smaller,


reusable objects like buttons and
lists, each commonly with its own
file. They are applied using classes,
with nested items classes
commonly prefixed with the
ancestor class:
.list { … }
.list--icon { … }
.list--text { … }

State styles are for changeable states,


like hidden or disabled. They are
commonly applied with class names
prefixed with ‘is-’ or ‘has-’ and chained
to other selectors:
.button { … }
.button.is-disabled { … }

Theme styles are optionally used


for changing the visual scheme.
SMACSS provides well-organised
CSS code split logically across
multiple files.
Using SMACSS does, however,
introduce specificity traps by
allowing IDs and relying on
selector chaining for state and
some layout declarations.

__________________________________________________
CSS METHODOLOGIES

s you have probably

A gathered from this article,


each CSS methodology
comes with its own benefits and
drawbacks. It is, however, possible
to combine aspects of multiple
methodologies together to create
your own custom one that works
best for you.
Let’s look at one way of
combining the four methodologies
discussed so far, for a site with a
homepage and a button
component, using Sass as a
preprocessor. Applying SMACSS
principles, we can divide our code
across multiple Sass partials as
shown opposite.

Then import them into ‘styles.scss’


that will be converted to ‘styles.css’
by Sass, as follows:
@import ‘base’;
@import ‘helpers’;
@import ‘components/button’;
@import ‘pages/home’;

Next we can add any styles that


override the browser defaults to
‘_base.scss’, allowing mainly
element selectors and their
pseudo-classes:
* { box-sizing: border-box; }

html,
body { height: 100%; }

a
{
&, &:active, &:focus, &:hover,
&:visited {
text-decoration: none;
}
}

Selector chains are sometimes


required to override unwanted
styles applied by external For each t we will have many m can
frameworks. For example, the a separat e ‘components’ find, ada iking,
‘Materialize.css’ framework applies directory BEM and stick tle
padding to grid columns using a methdology. We will allow BEM } point in creating a methodology if
two-class selector chain ‘.row .col’, formatted single-class selectors, you constantly deviate from it. If
making it impossible to override their pseudo-elements and an Finally, we can add page-specific you find yourself doing so, then
with a single-class BEM selector. infinite number of chained overrides to a corresponding file in incorporate these deviations into
Such overrides should also be pseudo-classes. For example, the the ‘pages’ directory. To ensure that your methodology in a way that is
added to ‘_base.scss’, for example CSS of buttons can be defined in ‘_ these overrides are always applied consistent and easy to understand.

feature _________________________________________________ 75
THE CUTTING EDGE OF

Stay on top of CSS trends, new features and new


properties to develop your design skills and make
award-winning websites
SS is one of the most important previously needed JavaScript, such as

C tools of any web designer, given


that it adds the design styling to
pages, but it has become far more
off-screen menus, drop downs,
lightboxes, accordians and parallax
scrolling. This makes your site more
important than that. Having the ability performant. Staying on top of trends
to put animation on pages and react to and new features is essential to
interactions is the central part of expanding your design skills towards
creating a compelling user experience. making award-winning websites. Check
CSS now performs many tasks that out the examples opposite.

CSS is the designer’s swiss army knife, specifically created to


add the design to your pages, it’s the magic that elevates your
design above your competitors
MARK SHUFFLEBOTTOM
Interaction Design Professor
twitter.com/webspaceinvader

76__________________________________________________feature
THE CUTTING EDGE OF CSS

CSS AND SVG


CLIPPING MASKS
landlifecompany.com
Land Life Company makes extensive
use of SVG clipping masks with CSS
to create this fully interactive image
mask with text masking for this
interactive discovery site.

BI-DIRECTIONAL SCROLLING
deanbradshaw.com
Unexpected scrolling always grabs the user’s attention.
Photographer Dean Bradshaw’s website moves subtle
background text horizontally across the screen as the user
scrolls downwards.

HEAT DISTORTION EFFECT


tympanus.net/Tutorials/HeatDistortionEffect
This effect isn’t that visible in the image, but SVG filters
can be used by CSS and animated so that heat
‘wobble’ displacement effects can be added to images.

feature _________________________________________________ 77
THE CUTTING EDGE OF CSS

WHAT’SHOTRIGHT NOW Here’s three CSS properties for you to try today

DESIGNING FOR DISPLAY CUTOUTS


developers.google.com/web/updates/2018/09/nic69
As the advent of phones with ‘cutout’ sections or ‘notches’
on the display rises, we as web designers have to think
about what that means for our designs on those pages.
Currently web browsers on these devices add an extra

TO FOLLOW
margin to accommodate these cutouts. Web designers
often like to use the full screen, and now there is a way to
do that, with Chrome leading the way. Add this meta tag
to the document:
RACHEL ANDREW <meta name=’viewport’ content=’initial-scale=1,
@rachelandrew viewport-fit=cover’>
Rachel is a CSS working group
expert and has been a strong Then use the CSS safe environment variables to layout
advocate for web standards. your content:
She is currently vocal in .content {
promoting the use of CSS Grid padding: 16px;
to design pages. padding-left: env(safe-area-inset-left);
padding-right: env(safe-area-inset-right);
ANA TUDOR }
@anatudor Now you just have to test your design in landscape and
Ana is an international speaker, portrait on the device.
covering workshops on

CSS CLIP PATH


cutting-edge CSS features.
You’ll also find her
demonstrating features of the codepen.io/bbx/pen/GYLOZd
CSS conical gradient. The CSS clip path is one of those properties that has really
helped push visual effects. Originally this was CSS clip,
MARY LOU and is used to clip out part of the element. There are a
@crnacura number of ways to use this, including inset, which would
Mary is constantly working inset the element by however many pixels on each side:
with CSS to develop unique clip-path: inset(10px 20px 30px 40px);
user experiences, and these
are often pushing the There is also polygon, which would enable multiple points
boundaries of what is currently to be added so some more obscure shapes can be made.
possible. Many of her Circle and ellipse are fairly straightforward, but it’s also
examples often show up on possible to reference a path from an SVG image as well:
award-winning sites. clip-path: url(path.svg#c1);
clip-path: polygon(5% 5%, 100% 0%, 100% 75%, 75% 75%,
JAMIE COULTER 75% 100%, 50% 75%, 0% 75%);
@jamiecoulter89 clip-path: circle(30px at 35px 35px);
Jamie pushes CSS to its clip-path: ellipse(65px 30px at 125px 40px);
absolute limits by creating
adventure games solely in CSS,

CSS CONIC GRADIENTS


without any JavaScript – which
sounds like an impossibility –
and these games are leaverou.github.io/conic-gradient
insanely cute! The conic gradient is very similar to a radial gradient.
However, you can’t create a colour wheel in radial
JEN SIMMONS gradient, but you can do that with a conical gradient.
@jensimmons Where radial gradients radiate between points, the
Jen is Designer Advocate at conical moves around a circle and blends between
Mozilla, responsible for colours. At first you may think this isn’t really anything
creating the Grid Inspector. special, but with a little creativity to add stops in the right
She teaches all over the web places there are some great results that can be achieved.
and at conferences on the At present this can only be achieved using a polyfill.
power of CSS for design. Check out Ana Tudor’s work with conical gradients.

78__________________________________________________feature
TH C T N EDGE F C

WHAT IS HOUDINI?
Every web designer has probably
tried to implement a new feature
of CSS but has been unable to
because browser support isn’t
Its plan is to there. Houdini is here to end that
The hello Houdini mini site has some good
visual examples. Here you can see a saw
introduce a new Houdini is a new W3C task force, and its
goal is to take away the problem of poor
tooth edge being used

series of APIs that support of new features on CSS. Its plan is

will open up the


TO FOLLOW
to introduce a new series of APIs that will
open up the power of CSS to the browser in

power of CSS to the JavaScript for the first time. This means that
CSS features can be coded by the designer
browser in JavaScript or developer and have all the native speed CSS-TRICKS
for the first time. This of regular CSS. All of this might sound a
little like overkill, to suddenly enable
@css
CSS-Tricks has long
means that CSS designers to extend CSS, but it will allow for
consistent coverage of a new CSS feature
Ana Tudor shows how Houdini can be used
to animate, transform and create some
established itself as a website
that showcases CSS features in
features can be
sophisticated 3D animation
and reduce the need for complicated great detail. Its Twitter account

coded by the polyfills that aim to backfill on older


browsers where there is spotty coverage.
gives the latest, up-to-date
news on CSS.
designer or developer You may be wondering if this is all CSS,
RESPONSIVE DESIGN
and have all the
and the answer to that would be no. The
way to think of this is that Houdini opens @rwd

native speed of low-level JavaScript APIs for the browser’s


render engine. It’s not ready for use yet,
Ethan Marcotte wrote the first
book on responsive design,
regular CSS and in order to get access you will need to
go to ‘chrome://flags’ in Chrome and Google shows some of its use cases for
and this Twitter account gives
you all the CSS responsive
Houdini. This example demonstrates
enable ‘Experimental Web Platform parallax scrolling running as a native information in one easy-to-
features’ to use it. CSS command find place.

CSS API
There are six APIs associated with what
CSS AWARDS
@cssawards
Houdini offers to the browser. Here three
of those are explored Selecting the best websites
that are developed with CSS
LAYOUT API PAINT API from around the world, this

MASONRY LAYOUT RIPPLE EFFECT


twitter account gives a great
information feed on what can
googlechromelabs.github.io/houdini-samples/ youtube.com/watch?v=BX_qv2yKSUk be designed with CSS.
layout-worklet/masonry The ripple effect shown in this example is the kind of
This is one of the Google Chrome Lab samples. In this effect that is found natively on Android devices, where THE CSS WORKING GROUP
example a native layout is created in CSS for a masonry- one part of something is tapped and the animation @csswg
style layout. The Chrome Labs site is a good resource, radiates from that point. The example is useful because The CSS Working Group is the
as all of the currently implemented APIs have source it’s on YouTube so is easy to see, and it demonstrates group that writes the CSS
code and examples available at this site. custom ‘painting’ to the browser renderer. specifications for the World
Wide Web Consortium (W3C)
ANIMATION API so that all internet browsers

CONTROLLING ANIMATION
adhere to the same standards.
it is a great resource on the

WITH SCROLLING
latest CSS.

houdini.glitch.me/animation CODROPS
This not only demonstrates the scrolling effect on the @codrops
page but also shows exactly how it was created, with a Codrops is a useful resource
tutorial explaining how the Animation API works. The for all things web
page also contains customisable code to experiment design-related, but more
with. Changing values will cause elements to scroll at specifically codrops has a
different speeds on the page. The rest of the site has strong slant towards the
great resources for explaining Houdini APIs. design styling of CSS.

feature _________________________________________________79
ON THE WEB SVG support is finally where is should be. So if you’re still
using PNG for logos, icons or interact elements, it’s high
time you learn about the power of Scalable Vector Graphics

SVG is now widely supported on all major browsers and


devices. They are super small, searchable, modifiable
via code and scalable. They look great at all sizes and
can be used just like images or inline right in your HTML
RICHARD MATTKA
Creative Director, Developer, Designer
richardmattka.com

80 _________________________________________________feature
SVG ON THE WEB

WHY USE SVG?


THERE ARE A HOST OF REASONS TO IMPLEMENT SVG. FIND OUT WHAT THEY ARE
With a desire for fast, responsive
experiences, SVG can make dramatic
improvements to your site. There are several
When it comes to logos, icons, interface elements and vector- great times to use SVG
based artwork that you’d like to look crisp, animate or make
responsive, there are plenty of reasons to use SVG.

1 PIXEL-PERFECT SCALING
Using PNGs or rasterised
images means you are
restricted to pixels. It also
3 SMALL FILE SIZE
PNGs can get large very
quickly, especially when you
need high-definition. The
WHAT IS SVG USED FOR?
LOGOS, UI ELEMENTS, ICONS AND ARTWORK ALL FIT THE PROFILE
means you are likely to have larger the file size, the SVG is heavily underused, partly because it took a long time for widespread support
multiple images for various longer it takes to load and to across browsers. With a desire for fast, responsive experiences, SVG can make
retina devices or resolutions. render. JPGs are better but dramatic improvements to your site. There are several great times to use SVG.
SVG is not affected by also large. That means
resolution or whether or not slower sites. SVG is just LOGOS AND ICONS ANIMATIONS
you have a retina display. SVG code, which means very Logos and icons often share a need to be SVG can work with CSS animations, so
images scale and always look small file sizes. Use it for clear and sharp at any size. Whether it’s a you don’t have to learn new animation
perfect because they are icons, logos and anything simple button or a large, screen-filling skills. SVG can also use its own built-in
drawn with code, not pixels. that can be created as billboard, you want the quality consistent and SMIL animation ability, which is even
vector art. crisp. SVG enables precise control of every more robust if you want to make really
2 MODIFIABLE shape, line and element. SVG icons and logos creative results.
SVG can be animated and 4 ACCESSIBILITY are more accessible, which means they’re
styled with CSS. You can SVG files are text-based and easier to position and manipulate in real-time. TRADITIONAL DRAWINGS & ILLUSTRATIONS
change colours, sizes, fonts and can be searched and indexed. Many traditional illustrations translate
so much more. Elements within This makes them readable by CHARTS, GRAPHS, INFOGRAPHICS really well to SVG, provided they are not
the SVG can be responsive as screen readers, search SVG can be updated dynamically to plot overly complex in details. Sketches and
well to use interaction. engines and other devices. data based on user actions or other diagrams to explain features of a
Animations that you use on Each element within the SVG data-driven events. This makes SVG product or illustrate a concept can work
HTML elements can also be is also accessible for search perfect for things like interactive maps very well.
used on SVG elements. but also manipulation. or graphics that illustrate data.
INTERFACES AND APPLICATIONS
Raster Vector VISUAL EFFECTS SVG is ideal for complex interfaces that
.jpeg .gif .png .svg Many real-time visual effects can be created can be integrated with web-based
using SVG, including shape morphing and applications and rich internet
transitioning from one shape to another. applications (RIAs). They are lightweight,
You can transform letters into shapes, logos easy to animate, and each element can
into other logos and much more. capture user interaction events.

BROWSER SUPPORT MOST MODERN WEB BROWSERS SUPPORT SVG. GREEN IS GOOD
Android Blackberry Chrome for
IE Egde Firefox Chrome Safari Opera iOS Safari Opera Mini Browser Browser Opera Mobile Android

2.1 - 2.3

6-8 2 3.1 3 - 4.3

9 - 10 12 - 16 3 - 62 4 - 69 3.2 - 11.1 10 - 55 3.2 - 11.4 4.4 - 4.4.4 7 12 - 12.1

11 17 63 70 12 56 12 ALL 67 10 46 69
source; caniuse.com

18 64 - 65 71 - 73 TP

feature _________________________________________________ 81
SVG ON THE WEB

ADD SVG TO THE PAGE


THERE ARE SEVERAL WAYS YOU CAN USE SVG ON YOUR WEBPAGES. LET’S HAVE A LOOK AT HOW A FEW OF THESE WORK
APPS FOR SVG
Since SVG is a text file, you can
use any text editor you like to
edit SVG manually. There are
USE THE <IMG> TAG INLINE SVG IN HTML also a number of great apps
To embed an SVG via an <img> element, you just need You can also open up the SVG file in any text editor, for quickly creating and
to reference it in the src attribute as you would with copy the SVG code and paste it into your HTML working with SVG
any image. You should define a height and width as document. We call this inlining SVG or using it inline.
well, the same as when you add images. Here is an SVG code elements begin and end with the <svg></
example of what the HTML code looks like: svg> tags. Here is a simple example of what you could
paste into your document:
<img src=”circle.svg” alt=”a red circle”
height=”100px” width=”100px” /> <svg width=”100” height=”100”>
<circle cx=”50” cy=”50” r=”40”stroke=”black”
The advantages to this method are that it is very stroke-width=”4”fill=”red” />
quick and easy to add. You can also wrap it in an <a> </svg>
tag to make it a hyperlink like a regular image. You ADOBE ILLUSTRATOR
can use CSS to affect the SVG image the same as any Putting your SVG inline saves HTTP requests and adobe.com/products/illustrator
other, but you cannot use JavaScript or external CSS therefore can reduce your loading time. You can Illustrator is easy to use and
to manipulate the content of this image. You can still assign classes and ids to SVG elements and style creates beautiful results. However,
use inline CSS in the SVG code itself if you edit the them with CSS, either within the SVG or wherever you the resulting SVG can have some
SVG code. put the CSS style rules for your HTML document. In quirks that make it necessary to
fact, you can use any SVG presentation attribute as a post-process to be perfect.
USE SVG IN CSS CSS property.
SVG images can be used as background-image in CSS SVG-EDIT
as well, just like PNG, JPG or GIF images. Here is an svg-edit.github.io/svgedit/releases/
example of including an SVG image in CSS: latest/editor/svg-editor.html
SVG-edit is a fast, web-based,
.element { background-image: url(/https/www.scribd.com/images/ JavaScript-driven SVG drawing editor
image.svg); } that works in any modern browser.

The advantages of SVG, such as crispness at any size, INKSPACE


are retained with this method. You can also do wacom.com/en/products/
anything a raster graphic can do, like repeat, scale, apps-services/inkspace
position and more. Ink to vector – keep your creative
ideas alive with this editable digital
You can use CSS to affect the SVG image the ink. Export your sketches and
same as any other, but you cannot use drawings to a scalable SVG format
for further editing and enhancing for
JavaScript or external CSS to manipulate the web and more.
content of this image
APACHE BATIK

CODING SVG
xmlgraphics.apache.org/batik
Batik toolkit is written in JavaScript
YOU CAN CODE SVG IN ANY TEXT EDITOR and offers almost complete SVG
SVG uses an XML-based language for describing vector images. It’s a markup language, like HTML, support. Batik includes a viewer
except that you have a wide variety of elements for defining the shapes to create these images, along (Squiggle), a rasteriser for PNG
with effects to apply to these shapes as well. output, an SVG pretty printer to
You can code SVG right along with your HTML in your favourite code editor. You can code them as format SVG files, and a TrueType-
separate files and include them, or you can code them inline in your HTML. As a simple example, the to-SVG-Font converter.
following code creates a circle and a rectangle:

<svg version=”1.1”
baseProfile=”full”
width=”300” height=”200”
xmlns=”http://www.w3.org/2000/svg”>
<rect width=”100%” height=”100%” fill=”black” />
<circle cx=”150” cy=”100” r=”90” fill=”blue” />
</svg>

82__________________________________________________feature
SVG ON THE WEB

MAKING SHAPES MAKING PATH


& CURVES
SVG MAKES IT EASY TO CREATE A NUMBER OF BASIC SHAPES

CIRCLES 1
There are three attributes to use to The <path> element is extremely powerful for making shapes. You can
create a circle. They include: use it to create lines, curves, arcs and more. You can even use it with
r - The radius of the circle. text to create text that flows along paths.
cx - The x position of the centre
of the circle. DRAWING LINES
cy - The y position of the centre To draw a line or curve, you use the path element and ‘define’ the path
of the circle. using the ‘d’ attribute. You can ‘move’ the start of a line using the ‘M’
command for absolute positioning and the lower case ‘m’ for relative
The code to draw a circle is very easy positioning. You use the ‘L’ command to draw a line to a new point. Here
to use. You can set the stroke colour is a quick example of a line:
and fill colour inline or separately as
well. Here’s an example: <path d=”M 10,10 L 250,250” fill=“transparent”
stroke=“black”/>
<svg width=”200” height=”250”>
2
<circle cx=”400” cy=”300” Here is an example of multiple lines, to show you how easy it is:
r=”200” stroke=”red” fill=
”transparent” stroke- <path d=”M 10,10 L 250,250 30,100 150, 50”
width=”5”/> fill=”transparent” stroke=”black”/>
</svg>

RECTANGLES
In a similar way to making circles,
you can create rectangles, using x
and y for position, then height and
width attributes to define the size.
The code looks like this:
3
<rect x=”100” y=”100” width=
”400” height=”300” stroke=
”black” fill=”transparent” DRAWING CURVES
stroke-width=”5”/> You can also use the ‘C’ command to draw curves. Use the ‘M’
command to set the start position, and then list the start, the anchor
LINES point and the end point like this:
Lines in SVG are for straight lines.
They take as attributes two points <path d=”M50 50 C 50 50, 150 100, 250 50” stroke=”black”
that specify the start and end point fill=”transparent”/>
of the line. Here’s an example:
You can also string curves together using the ‘S’ command to make
<line x1=”100” x2=”500” y1= even more complex curves like this:
”110” y2=”450” stroke=”orange”
stroke-width=”5” /> 4 <path d=”M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80”
stroke=”black” fill=”transparent”/>
POLYGONS
You can also create any kind of
polygon shape using the polygon
element, which will conveniently
return to the first point for you
after the end of your list of points.
Here’s a quick example of drawing
a polygon:

<polygon points=”50 160, 55 There are plenty of curves and paths you can create. There is a great
180, 70 180, 60 190, 65 205, resource for learning even more about paths here: developer.mozilla.
50 195, 35 205, 40 190, 30 org/en-US/docs/Web/SVG/Tutorial/Paths
180, 45 180”/>

feature _________________________________________________83
SVG ON THE WEB

MAKING TEXT & PATH


CREATE TEXT QUICKLY AND EASILY AND CUSTOMISE WITH A FEW ATTRIBUTES
RESOURCES
Learn more with these
great resources

MOZILLA DE ELOPER
Making text is easy in SVG. You use <text> NETWORK (MDDN)
the <text> tag to define it. Here is This is <tspan font-weight= developer.moziilla.o
a org/kab
g kab/docs/
an example: ”bold” fill=”red”>bold and Web/SVG
red</tspan> A greatt resource for learning the
<text x=”10” y=”10”> </text> We use the direction style and set it ins and outs of SVG, with many
This is text.</text> to ‘rtl’, which means right to left. We examples to help get you up
also have to set the unicode-bidi and running.
The x and y determine the position style to ‘bidi-override’.
of the text. Like with the shape CSS-TRICKS -
elements, text can be colourised USING TEXTPATH EVERYTHING YOU NEED
with the fill attribute and given a You can also set strokes, fills, This element uses the xlink:href TO KNOW ABOUT SVG
stroke with the stroke attribute. You rotations, direction and much more. attribute to connect to a path and css-tricks.com/lodge/svg
can even use gradients and patterns Here is a quick example of setting aligns the characters along this path. CSS-Tricks hosts a complete SVG
as strokes and fills. the text to draw outlines only, and to This enables you to draw virtually video tutorial series here. It
switch the direction of the text: any path you wish, and then attach covers what SVG is, why use it,
SETTING FONT PROPERTIES your text to it, so it follows it. Here’s how to use it and much more.
Each of the following properties <text x=”350” y=”50” an example:
can be set as an attribute or via a style=”fill: none; stroke: ENVATOTUT
V S-
CSS declaration: font-family, #000000; font-size: 48px; <path id=”my_path” d=”M 40,40 HOW TO HAND CODEE SV
S VG
font-style, font-weight, font-variant, direction: rtl; unicode-bidi: C 200,100 10,100 520,200” webdesigngn.tutsp
tutspluss.com/
font-stretch, font-size, font-size- bidi-override;”> fill=”transparent” /> tutorial
als/how-to-hand-code-svg--
adjust, kerning, letter-spacing, This is text <text> cms-330368
word-spacing and text-decoration. </text> <textPath xmlns:xlink=” envato otuts
uts hass a nice in-depth
th
Like the <span> elements <tpsan> http://www.w3.org/1999/xlink” tutori
rial that dives into many
can also be used to select web xlink:href=”#my_path”> gre
eat examples of hand-codin ng
sections of your text. A typical This Text is Curved SVGG, including rreusing SVG in
use-case might be to bold some </textPath> yourr page.
text like this: </text>

WHAT ABOUT SVG 2?


CSS & SVG
You can use CSS styles inline, inside
Use inline or
external CSS
on your page. For example, if you
SVG 2.0 – a brand new SVG
SVG 2.0 is currently in candidate
recommendation stage, which
SVG elements. Here is an example: set a class attribute on your SVG means it is not supported by
shape, you can set its colour browsers yet, and it may still be

SVG 2.0 is currently in <svg width=”350” height=”60”>


<text>
through regular CSS like this: some time before it is. It boasts
numerous improvements and
candidate This is <tspan font-weight <svg class=”logo” width=”400” features. It also removes or

recommendation stage,
=”bold” fill=”red”>bold height=”400” viewBox=”0 0 400 deprecates some features of SVG 1.1
and red</tspan> 400”> and incorporates new features from
which means it is not </text>
<style><![CDATA[
<rect class=”box” x=”0”
y=”0” width=”400” height=
HTML5 and Web Open Font Format.
SVG 2.0 removes several font
supported by browsers text{ ”400” fill=”#56A0D3” /> elements, such as glyphs, and they

yet, and it may still be dominant-baseline: hanging;


font: 28px Verdana, Helvetica,
</svg> are replaced by the WOFF font
format. Also the xml:space attribute
some time before it is. Arial, sans-serif;
}
And the CSS would be: is deprecated in favour of CSS.
It reached candidate
It boasts numerous ]]></style> .box { fill: red; } recommendation stage on 15

improvements </svg>
Notice we had inline colouring
September 2016. The latest draft
was released on 18 October 2018.
and features You can also use CSS separately,
just like with any other elements
that we then overrode with our
CSS. Pretty cool!
You can read more about it and
follow its progress here: w3.org/TR/
SVG2

84 _________________________________________________feature
The number one
destination for web design
news, views and how-tos.
Get Creative
Bloq direct to
your inbox with
our weekly
web design
newsletter

Graphic design Web design 3D Digital art

www.creativebloq.com
Tutorials

Manage React
application data
with Redux Create an API-powered state application and discover
the benefits of a centralised data store

DOWNLOAD TUTORIAL FILES


www.filesilo.co.uk/webdesigner
86 _________________________________________________tutorial
SUBSCRIBE TODAY Go to pa e 50 to learn more Tutorials

T
he appetite for single-page applications to the directory in the command line and install the 4. Set up root reducer
is greater than ever. Instead of a dependencies. Yarn is required to manage those A reducer is a function that knows how to update the
complete page reload each time the user dependencies, if this hasn’t been downloaded already. store. The store only deals with one reducer. We can use
clicks a link or fills a form in, we can Then start the development server. Redux’s ‘combineReducers’ method to split that into
provide real-time feedback using JavaScript and do the > yarn separate, smaller reducers that each have a specific role,
heavy lifting in the background. As developers, we have > yarn start such as storing information about the photos or the state
greater control over the data that gets transferred, and of the interface. Our first reducer will hold the photos
the user enjoys a faster, seamless experience – it’s a 2. Initialise the store within the gallery. Open up ‘reducers/root.js’ and import
win-win. The store is the heart of Redux. It holds the state of the that reducer in.
But without that constant connection back to the application and orchestrates all communication to and import { combineReducers }
server, the state of the application has to live on the from it. There should only ever be one store per from "redux";
client-side. Frameworks like React are great at storing application. Open up ‘index.js’ and create a store. This is import photos from "./photos";
state at a component level but start to struggle when done using the ‘createStore’ function from Redux. Pass in const rootReducer = combineReducers({
dealing with large sets of application-wide data. Explicitly the root reducer, which we will come to later. photos
passing that data through as props can clutter up the import { createStore } from "redux"; });
code and increases the surface area for bugs to appear. import rootReducer from export default rootReducer;
Redux takes the state of an application and places it in "./reducers/root";
one location. By combining with React, we can have the const store = createStore( 5. Create photos reducer
whole interface powered by a centralised data store. This rootReducer); When a reducer is called, it gets passed the current state
makes an application more reliable, more testable, and from the store and an object describing a change to the
when issues do arise they become easier to replicate. 3. Pass in the store state known as an ‘action’. The return value of the reducer
This tutorial is the first in a five-part series where we will Before React can use any data from the store, it needs to is what then becomes the store’s new state. Open up
be building PhotoShare – an application that allows be given access to it. The ‘react-redux’ package has a ‘reducers/photos/photos.js’ and create our first reducer.
visitors to comment directly on a set of photos. While it <Provider> component that can provide access to any For now, every action will return the state straight back
seems simple on the outside, there is lots to keep track of, component that requests it. Import the <Provider> without any updates.
from photos to the users and their comments. component and wrap it around the rendered content. const initialState = {};
In this part of the tutorial we will cover the basic Now we can start pulling in the state data wherever the export const reducer =
concepts around Redux, such as actions, reducers and application needs it. (state = initialState, action) => {
the data store. Later in the series we will use these import { Provider } from "react-redux"; return state;
concepts to power interactions such as form filling or […]
server communication. ReactDOM.render(

1. Install dependencies
<Provider store={store}>
<BrowserRouter>
Use more than switch
Redux does not specify the shape of a reducer.
Before we get started, we need to download all the files <App /> While a switch statement is most common, use
needed to run this application. Inside ‘package.json’ we </BrowserRouter> what makes sense for the application. The
can see the dependencies, including React, Redux and </Provider>, structure does not matter so long as the state
the ‘react-redux’ package that deals with the connection document.getElementById("root") object is returned.
between the two. Download the project files, then head );

Above
Starting the development server
should also open up the application in
the default browser. If it does not, head
to http://localhost:3000

Right
While developing the application it will
display full-screen errors as well as
the usual console ones. When built for
production, these do not appear

tutorial _________________________________________________ 87
Tutorials
Manage React application data with Redux

}; photos/photos.js’ and create a selector that gets all the export const mapStateToProps =
export default reducer; photos for the gallery. state => ({
export const getGalleryPhotos = photos: getGalleryPhotos(state)
6. Apply initial state state => Object.values(state.photos); });
Each reducer is likely to have data stored in an expected export default connect(mapStateToProps)
shape, such as an array or an object to hold specific 8. Connect with Redux (GalleryContainer);
information about that part of the state. We can initialise it For React components to access the store we created in
with a set of values from the outset. For this application step 3, we need to connect them to Redux. To do this we 10. Select a photo
we will pre-fill the photo data locally. Usually this would use ‘connect’ from the ‘react-redux’ package. ‘connect’ is With the gallery complete, we still need a way to view
come from a remote server and would initially be empty. an example of a higher-order component – an established specific photos in more detail. Clicking a photo in the
Import the example response and provide it as initial state React pattern that provides functionality to a passed gallery shows us a <Photo> component on its own page,
to the reducer. component. Head to ‘components/container/Gallery/ but it’s currently blank. Create another selector in
import exampleResponse from Gallery.js’, import ‘connect’ and use it to replace the ‘selectors/photos/photos.js’ to select a specific photo. We
"../../example-response"; exported component. can re-use the logic of ‘getGalleryPhotos’ like we would
const initialState = exampleResponse; import { connect } from "react-redux"; any other function.
[…] export const getPhoto = (state, id) =>
7. Select the photos export default getGalleryPhotos(state)
While not strictly required by Redux, selector functions connect()(GalleryContainer); .find(photo => photo.id === id);
are a useful way to get exactly what you need out of the
store. They filter out the rest of the data to leave only what 9. Map state to props 11. Link single photo
is needed for each component. Open up ‘selectors/ There are two parameters we can pass to ‘connect’. The As this component is not linked to <Gallery>, we need to
first is a special function that allows us to pass parts of the connect it to Redux separately. We can use the same
state from Redux into components. The ‘connect’ approach to pull information out using ‘mapStateToProps’
How many function gets the state from the store and passes it to and the new selector. Open ‘components/container/
connections? selectors. Selectors then get what they need and return it
to the component as a prop. Create this
Photo/Photo.js’ and connect this component to the store.
import { connect } from "react-redux";
Connecting too many components couples an
application closer to Redux, while too few ‘mapStateToProps’ function and use it to pass the ‘photos’ import { getPhoto } from
re-renders parent components unnecessarily. It’s prop into <GalleryContainer>. We can now see the images "../../../selectors";
important to find a balance that works best in start to appear in the gallery. export const mapStateToProps =
each application. import { getGalleryPhotos } (state, props) => ({
from "../../../selectors"; photo: getPhoto(state)

88 _________________________________________________tutorial
Tutorials
Manage React application data with Redux

The Redux data lifecycle


At its core, Redux is a set of functions and
dispatch(action) reduce(statr, action) objects with specific jobs to do. By ensuring
each part stays separate and communicates
in a defined way, Redux can help keep the
ACTION CREATOR STORE REDUCER state of an application up to date all from
one place.
The application’s state lives within the
state: {...} store. We can use selectors to pick out the
relevant parts of that state and pass it on to
the components that need it.
The only way to update the data in the
SELECTOR SELECTOR SELECTOR store is through an action, which is typically
triggered by a user. The action creators
showComment(3) photo: {...} make objects based on parameters, which
are then passed to each reducer connected
to the store. They check the action, perform
some modification to the state and return a
CONTAINER CONTAINER new copy for the selectors to use.
COMPONENT COMPONENT Each part of this process can be built
upon and expanded without affecting the
rest. This means that as the application
grows the data store can scale with it.

}); className to only show up when the ‘isCommentOpen’ commentOpen: undefined


export default connect( prop is true. };
mapStateToProps)(PhotoContainer); <div className={`comment__box export const reducer = (
comment__box--${direction} ${ state = initialState, action) => {
12. Pass through ID isCommentOpen ? "comment__box--open" switch (action.type) {
The selector still requires an ID to get the correct photo : "" default: return state;
from the store. The ‘mapStateToProps’ function has a }`} }
second argument that passes through the component’s > };
current prop values. The routing within the application export default reducer;
provides the ID of the photo, which is passed as an ‘id’ 15. Create UI reducer
prop. Update ‘mapStateToProps’ to use this new ID. We need to record which comment is currently open in 16. Link the reducer
Clicking on the first photo in the gallery now shows a the store. As it’s not directly related to a photo, we should Before Redux can access our new reducer, we need to
larger version. create a new reducer to handle this part of the state. pass it through to the root reducer. Go back to ‘reducers/
export const mapStateToProps = Open ‘reducers/ui/ui.js’ and create a reducer similar to the root.js’ and add the new UI reducer into the call to
(state, props) => ({ one for photos. ‘combineReducers’. Any UI data inside the store can now
photo: getPhoto(state, props.id) const initialState = { be accessed under the ‘ui’ property.
});

13. Show comment


In this application, users can leave comments on a
specific part of the photo. These will be displayed as an
overlay on the image itself. Open up ‘components/
presentational/Photo/Photo.js’ and start adding
comments after the <img> component. Pass all the data it
needs as separate props.
import Comment from
"../../container/Comment";
[…]
{comments.map(({ comment, id, left,
top, user }) => (
<Comment comment={comment}
id={id} key={id} left={left}
top={top} user={user}
/>))}

14. Hide other comments


Inside the <Comment> component, the ‘comment__box—
open’ class is causing all of the comments to display at
once. We can use Redux to only show the active
comment. Head to the component at ‘components/ 13
presentational/Comment/Comment.js’. Update the

tutorial _________________________________________________89
Tutorials
Manage React application data with Redux

Debugging with
Redux DevTools
With Redux quietly running in the
background, it can be difficult to know
exactly what’s going on. We could log
out each new state as an action comes
in, but this seems unsuited and noisy.
Thankfully there is a browser
extension available that can tap into a
Redux store and even manipulate it in
real time. Not only can it track actions
and show the current store state, but
also undo those actions to help see
how the application changes.
It taps into the store through an
‘enhancer’ – a module with access to
the API behind Redux to extend its
behaviour. It is recommended that this
enhancer is removed when building
the application for production.
The extension is available for
Chrome and Firefox. For more
information head to github.com/
zalmoxisus/redux-devtools-
extension

import ui from "./ui"; import { connect } from "react-redux"; import { HIDE_COMMENT, SHOW_COMMENT }
const rootReducer = combineReducers({ import { isCommentOpen } from from “../../constants/actions”;
photos, "../../../selectors"; […]
ui
}); export const mapStateToProps = case HIDE_COMMENT:
(state, props) => ({ return {
17. Create an open selector isCommentOpen: isCommentOpen( ...state,
With the UI state now in place, we can check to see which state, props.id) commentOpen: undefined
comment is open. Go to ‘selectors/ui/ui.js’ and add an }); };
‘isCommentOpen’ selector. By passing the ID of the
current comment, we can check it against the state. If the export default connect(mapStateToProps) case SHOW_COMMENT:
comment is open, then the selector returns true and (CommentContainer); return {
the comment appears. ...state,
export const isCommentOpen = 19. Toggle comment actions commentOpen: action.payload };
(state, id) => To tell Redux which comment should be visible, we
state.ui.commentOpen === id; need to dispatch an action to the reducers. By using 21. Dispatch new actions
action creator functions, we can be sure that the action The ‘connect’ higher-order component takes a second
18. Connect the comments object looks the same each time. Add a couple of function, which gives access to the ‘dispatch’ method
Now everything is set up, we can connect each action creators in ‘actions/ui/ui.js’ to show and hide a from Redux. In short, this ‘mapDispatchToProps’ function
<Comment> component to the store, like with <Gallery>. comment by ID. We use constants for the type so they works similar to ‘mapStateToProps’ but allows us to
Head over to ‘components/container/Comment/ can match up with the reducer later on. dispatch actions. Back in ‘components/containers/
Comment.js’ and connect everything up like before. Pass import { HIDE_COMMENT, SHOW_COMMENT } Comment/Comment.js’, hook up ‘mapDispatchToProps’
the new selector inside ‘mapStateToProps’. from "../../constants/actions"; to pass through functions that can be called when a
export const hideComment = () => ({ comment is clicked.
15 type: HIDE_COMMENT import { hideComment, showComment }
}); from “../../../actions”;

export const showComment = id => ({ export const mapDispatchToProps =


type: SHOW_COMMENT, (dispatch, props) => ({
payload: id hideComment: () =>
}); dispatch(hideComment()),
showComment: () =>
20. Update the UI reducer dispatch(showComment(props.id))
When either action is dispatched it ends up passing });
through the UI reducer we created earlier. By using the
‘type’ property in the action, we can match an action to a export default connect(
change in the store. Add cases for the actions in mapStateToProps,
‘reducers/ui/ui.js’. These will either record or clear the mapDispatchToProps
open comment ID. )(CommentContainer);

90 _________________________________________________tutorial
Discover another of our great bookazines
From science and history to technology and crafts, there
are dozens of Future bookazines to suit all tastes
Get your listing in our directory
To advertise here call the ads team on 01225 442244

HOSTING LISTINGS
Featured host: Netcetera
netcetera.co.uk
03330 439780

About us
Formed in 1996, Netcetera is one of infrastructures. A state-of-the-art data
“ Premier provider of
data centre colocation, cloud
hosting, dedicated servers
Europe’s leading web hosting service centre environment enables Netcetera and managed web hosting
services in the UK

providers, with customers in over 75 to offer your business enterprise-level
countries worldwide. colocation and hosted solutions.
As the premier provider of Providing an unmatched value for your
data centre colocation, cloud hosting, budget is the driving force behind our
dedicated servers and managed web customer and managed infrastructure
hosting services in the UK, Netcetera services. From single server to fully
offers an array of services designed to customised data centre suites, we focus
more effectively manage IT on the IT solutions you need.

What we offer sData centre colocation –


sManaged hosting – A full Single server through to full
range of solutions for a cost- racks with FREE setup and a
effective, reliable, secure host. generous bandwidth.

sCloud hosting – Linux, sDedicated servers – From


Windows, Hybrid and Private QuadCore up to Smart Servers
Cloud Solutions with support with quick setup and
and scalability features. fully customisable.

5 tips from the pros knowledgeable staff available 24/7 to


1. Reliability, trust & support provide you with assistance when you
Reliability is a major factor when it need it most. Our people make sure
comes to choosing a hosting partner. you are happy and your problems are
Netcetera guarantees 100 per cent resolved as quickly as possible. Testimonials
uptime, multiple internet routes with Roy T
the ability to handle DDOS attacks, 4. Value for money “I have always had great service from Netcetera. Their technical support is
ensuring your site doesn’t go down We do not claim to be the cheapest second to none. My issues have always been resolved very quickly”
when you need it. service available, but we do claim to
offer excellent value for money. We also Suzy B
2. Secure and dependable provide a price match on a like-for-like “We have several servers from Netcetera and their network connectivity is
Netcetera prides itself on offering its basis, as well as a price guarantee for top-notch, with great uptime and speed is never an issue. Tech support is
clients a secure environment. your length of service. knowledgeable and quick in replying. We would highly recommend Netcetera”
It is accredited with ISO 27001 for
security along with the options of 5. Eco-friendly Steve B
configurable secure rackspace available Netcetera’s environmental commitment
in various configurations. is backed by use of eco-cooling and
“We put several racks into Netcetera, basically a complete corporate backend.
They could not have been more professional, helpful, responsive or friendly. All
hydroelectric power. This makes
the team were an absolute pleasure to deal with, and nothing was too much
3. 24/7 technical support Netcetera one of the greenest data
trouble, so they matched our requirements 100 per cent”
Netcetera has a committed team of centres in Europe.

92__________________________________________________ listings
Supreme hosting SSD web hosting

cwcs.co.uk bargainhost.co.uk
0800 1 777 000 0843 289 2681
CWCS Managed Hosting is the UK’s Since 2001, Bargain Host have
leading hosting specialist. They offer a campaigned to offer the lowest possible
fully comprehensive range of hosting priced hosting in the UK. They have
products, services and support. Their achieved this goal successfully and built
highly trained staff are not only hosting up a large client database, which includes
experts, they’re also committed to many repeat customers. They have also
delivering a great customer experience won several awards for providing an
and are passionate about what they do. outstanding hosting service.
sShared hosting
sColocation hosting sCloud servers
sVPS sDomain names
s100 per cent network uptime Budget hosting with high-performance hosting products
as well as the infrastructure for the
efficient operation of sites. A combination
UK-based hosting of stable technology, attractive pricing, Agency hosting specialist
flexible support and services has enabled
hetzner.com Hetzner Online to strengthen its market
+49 (0)9831 505-0 position nationally and internationally.
Hetzner Online is a professional web nimbushosting.co.uk
cyberhostpro.com hosting provider and experienced data sDedicated/shared hosting 02031266781
0845 5279 345 centre operator. Since 1997, the company sColocation racks Nimbus Hosting have partnered with
Cyber Host Pro are committed to has provided private and business clients sSSL certificates agencies to develop our revolutionary
providing the best cloud server platform STORM. With a team dedicated
hosting in the UK; they are obsessed to outstanding support, our 5-star Google
with automation. If you’re looking for a reviews truly speak for themselves. Join
hosting provider who will provide you the thousands of agencies and
with the quality you need to help your freelancers who are benefitting from a
business grow, then look no further control panel that speeds up your website
than Cyber Host Pro. developement as well as your client’s
websites. Supercharge your digital
sCloud VPS servers projects today with STORM.
sReseller hosting s TFDPOE 8PSE1SFTT JOTUBMM
sDedicated servers s %FQMPZ EJSFDUMZ GSPN (JU)VC
s &BTZ UFBN NBOBHFNFOU

Cluster web hosting


Flexible cloud servers

fasthosts.co.uk elastichosts.co.uk
0808 1686 777 All-inclusive hosting operates across ten countries. With a 020 7183 8250
6,CBTFEBOEPQFSBUJOHGSPN comprehensive range of high- ElasticHosts offer simple, flexible and
dedicated UK data centres. Fasthosts performance and affordable products, 1&1 DPTUFŇFDUJWF DMPVE TFSWJDFT XJUI
keep over 1 million domains running offers everything from simple domain high performance, availability and
smoothly and safely each day. Services registration to award-winning website scalability for businesses worldwide.
can be self-managed through the 1and1.co.uk building tools, eCommerce packages and Their team of engineers provide
Fasthosts Control Panel. 0333 336 5509 powerful cloud servers. excellent support 24/7 over the phone,
1&1 Internet is a leading hosting by email and with a ticketing system.
sDedicated servers provider that enables businesses, sEasy domain registration s Cloud servers with any OS
sCloud servers developers and IT pros to succeed sProfessional eShops s Linux OS containers
sHosted email online. Established in 1988, 1&1 now s)JHIQFSGPSNBODFTFSWFST s 24/7 expert support

listings__________________________________________________ 
Get your listing in our directory
To advertise here call the ads team on 01225 442244

COURSE LISTINGS
Featured:
Northcoders
northcoders.com
Twitter : @northcoders


Facebook: Northcoders
No matter what your
About us
Northcoders is the coding bootcamp full-time bootcamp, or fit their course
background, you can
for the north, based in the heart of around your life with their 24-week fast-track your career and
Manchester and built upon northern
values of grit, determination and
part-time bootcamp. Their internal
career support team will help find you
become a web or software
developer in 12 weeks

community spirit. No matter what work as a developer, setting up .
your background, you can fast-track interviews with your choices of
your career and become a web or Northcoders Hiring Partners across
software developer in 12 weeks at their the north of England.

What we offer
s 'VMMUJNF s 1BSUUJNF
Fast-track your career Fit our curriculum around
in just 12 weeks your life in 24 weeks

5 tips from the pros


 (FU TUBSUFE XJUI DPEJOH for you, set aside a few evenings
The best way to know if coding each week to really start making
is for you is to just try it! We progress! If coding is for you,
recommend the free, online this should be fun.
JavaScript track of
Codecademy to get you  #F QSFQBSFE
started with the basics. We’ll be with you every step of
the way when you apply. Make
 %P ZPVS SFTFBSDI sure you go through all the
Make sure you read plenty materials we recommend and
of student reviews to make ask for help if you’re stuck.
sure you’re applying
somewhere reputable. Read  (FU TPDJBM
their blog and have a look at With Northcoders, you’re not
their social channels. just on a course, you’re part of a
community that will stay with
 5ISPX ZPVSTFMG JO you long after you graduate.
Once you’ve decided it’s right Make the most of it!

Becoming part of this vibrant, caring community was Northcoders delivered their part of the bargain in spades.
something I hadn’t expected before the course, but They provided tremendous assistance in turning me into
now I couldn’t be without it. To be a Northcoder is to the full product – a well-rounded, capable future tech
be enlightened, inspired and supported employee – and they have the contacts to deliver the
Joanne Imlay opportunities for such people.
Primary school teacher to software developer at Careicon Joe Mulvey
Maths teacher to software developer at Auto Trader

94 _________________________________________________ listings
WE GOT CODERS

UDEMY
udemy.com wegotcoders.com
[email protected]
Twitter: @udemy We Got Coders is a consultancy that
Facebook: udemy provides experts in agile web
development, working with startups,
The inspiration for Udemy began in a agencies and government. Take one of
small village in Turkey, where founder their 12-week training courses that covers
Eren Bali grew up frustrated by the all that is required to become a web
limitations of being taught in a developer, with highly marketable
one-room school house. Realising full-stack web development skills.
the potential of learning on the internet,
he set out to make quality education sClassroom-based training
more accessible. Udemy is now a sReal-world work experience
global marketplace for learning and sEmployment opportunities
teaching online. Students can master
new skills by choosing from an
extensive library of over 40,000 FUTURELEARN
courses, including HTML, CSS, UX,
JavaScript and web development.

40,000+ courses: There is a


course for every designer and dev. futurelearn.com
Self-paced learning: Learn how [email protected]
to code at your own pace. Choose from hundreds of free online
courses, from Language & Culture to
Business & Management, Science &
Technology to Health & Psychology.
THE Learn from the experts. Meet educators
IRON YARD from top universities who’ll share their
experience through videos, articles,
theironyard.com quizzes and discussions.

Twitter: @TheIronYard sLearn from experts


Facebook: TheIronYard sFree courses
sAll-device access
The Iron Yard is one of the world’s
largest and fastest growing in-person
code schools. It offers full-time and GYMNASIUM
part-time programs in back-end
engineering, front-end engineering,
mobile engineering and design. The
Iron Yard exists to create real, lasting
change for people, their companies thegymnasium.com
and communities through technology [email protected]
education. The in-person, immersive Gymnasium offers free online courses,
format of The Iron Yard’s 12-week designed to teach creative
courses helps people learn to code professionals in-demand skills.
and be prepared with the skills needed Courses are all self-paced and taught by
to start a career as junior-level experienced practitioners with a passion
software developers. for sharing practical lessons from the
design trenches.
12-week code school: Learn
the latest skills from industry pros. sGain real-world skills
Free crash courses: One-night sGet expert instruction
courses, the perfect way to learn. sCareer opportunities

listings__________________________________________________95
Free with
your magazine
Essential assets Exclusive Tutorial Plus, all of this
and resources video tutorials project files is yours too…
Get textures, fonts, Learn to code/create $OOWKHDVVHWV\RX·OOQHHG ‡$OOQHZWXWRULDOILOHVWRKHOS\RX
backgrounds and more with HTML, CSS & JS to follow our tutorials PDVWHUWKLVLVVXH·V+70/&66
and JavaScript techniques
‡1HZFKDSWHUVIURP.LOOHUVLWHV
expert PHP video courses
(shop.killervideostore.com)
‡/XPLQRXVSUHVHWVDQGL3DG
Pro hi-res mockups from
Sparklestock worth $36
(www.sparklestock.com)

Log in to www.filesilo.co.uk/webdesigner Free


for digital
Register to get instant access readers, too!
to this pack of must-have Read on your tablet,
download on your
creative resources, how-to computer
videos and tutorial assets
The home of great
downloads – exclusive to
your favourite magazines
from Future!
Secure and safe online
access, from anywhere
Free access for every
reader, print and digital
Download only the files
you want, when you want
All your gifts, from all your
issues, in one place

Get started
Everything you need to
know about accessing
your FileSilo account
Unlock
every
issue

 Follow the instructions on


screen to create an
account with our secure FileSilo
system. Log in and unlock the
issue by answering a simple
question about the magazine. gifts from more than 70 issues
Access our entire library of resources with a money-saving
VXEVFULSWLRQWRWKHPDJD]LQH²WKDW·VPRUHWKDQIUHHUHVRXUFHV

Over 70 hours More than Over 250


of video guides 400 tutorials creative assets
 You can access FileSilo
on any computer, tablet
or smartphone device using any
Let the experts teach you Get the code you Templates, fonts, textures
to create and code need to get creative and backgrounds
popular browser. However, we
recommend that you use a
computer to download content,
as you may not be able to
download files to other devices.

Head to page 50 to subscribe now


 If you have any
problems with
accessing content on FileSilo,
Already a print subscriber?
+HUH·VKRZWRXQORFN)LOH6LORWRGD\«
More thhan
More
take a look at the FAQs online
or email our team at the
Unlock the entire Web Designer FileSilo library with your
unique Web ID – the ten-digit alphanumeric code printed above
90
00 re
easoonss added
every
address below:
[email protected]
your address details on the mailing label of your subscription
copies – also found on any renewal letters. to
o sub
bscriibe issue
NEXT MONTH
JAVASCRIPT
2019
25 APIs, frameworks and tools that designers
and developers will need in their toolbox

WHAT'S NEW IN CSS CUSTOM REACT AND


WORDPRESS 5? PROPERTIES REDUX THUNK
What does the Gutenberg editor have to offer, and Learn how to use new media query '@media Learn how to deal with fetching/receiving data
what are the pros over previous versions? (prefers-color-scheme: dark)' from a server, handling latency and errors

Visit the WEB DESIGNER online shop at ALL IN YOUR NEXT


WEB DESIGNER
myfavouritemagazines.co.uk Issue 283 on sale
for the latest issue, back issues and specials Tuesday 8 January 2019
SUBSCRIBE TODAY Go to pa e 50 to learn more
98 __________________________________________next month

You might also like