How Does Free Graphic Design Software Stack Up?

Original Source: https://inspiredm.com/how-does-free-graphic-design-software-stack-up/

Graphic design is an easy kind of business to manage, but a difficult one to get started in. Until you have built up a decent number of regular clients, you may find you must watch every penny closely. If you are in this situation, the prices of popular graphic design software will be quite a shock.

One of the true luxuries of running your own graphic design studio, however, is that you’re not locked in to using any particular software as you would probably be if you were an employee of somebody else. That means you’re at liberty to use whatever helps you get the job done efficiently.

The idea of free graphic design software may sound exciting, but is it really up to the task? Will it allow you to create professional quality work without the high cost? Let’s find out.

1. PhotoShop vs GIMP

 GIMP default interface

GIMP is often touted as a replacement for PhotoShop, but this isn’t strictly true. GIMP does not come with everything PhotoShop has, because the GIMP developers wanted to create a lean application that does not have bloat. In consequence, most of those “missing” features are still available, but have to be added in after you have installed GIMP.

You can do almost anything in GIMP that you can do in PhotoShop, but some things (like creating primitives) require additional steps. Previously GIMP didn’t have as many features as PhotoShop, but it is gradually drawing level, and may one day overtake it.

 GIMP in Single Window mode

GIMP advantages:

Free. You’ll save at least $600 compared to buying PhotoShop, and significantly more over the long term because there’s no upgrading or subscription fees.
Open source. This is good for many reasons too complex to tackle in this article, however you can read Advantages of Open Source Software if you want a quick summary of the primary advantages.
Cross-Platform. GIMP works on just about every major operating system, plus a few minor ones. PhotoShop definitely does not do that.
No licensing worries. Because it’s free, GIMP can be installed on as many computers as you want, and it can be shared freely.
Easier to use. A bit of a controversial point because people who have a lot of experience in PhotoShop don’t relish the idea of learning a new system, but GIMP actually is a lot easier to use.
Dockable detached tool bars. Most people who are migrating from PhotoShop will initially prefer GimpShop or GimpPhoto instead of authentic GIMP, but actually the detached toolbars of GIMP are a strength, not a weakness. If you’re not aware of their power, it’s because you’re not working in a multi-screen environment (and you definitely should be).  You can throw all your tool bars onto one screen and work on the image in the other, which means you can see more of your image at a higher zoom level, with no pesky toolbars getting in the way.
One-way PhotoShop compatibility. This means you can open PhotoShop images in GIMP, use most PhotoShop filters and brushes in GIMP, and export GIMP files to PhotoShop format. However the reverse is not true. PhotoShop can’t open GIMP files, save to GIMP format, or use brushes and filters that were designed exclusively for GIMP.
Uses less resources. PhotoShop is a hungry beast in comparison to GIMP. The entire core GIMP package installs in under 20MB of space, while PhotoShop requires about a gigabyte. PhotoShop also typically uses more CPU and RAM resources while running.

PhotoShop default interface

Advantages of PhotoShop:

Higher level of industry recognition. PhotoShop has for many years been so far at the top of image editing tools, it has almost achieved the same status in that field as Google has achieved in online searches.
Adjustment levels. You may need these, but not everyone does. GIMP only uses physical image layers.
Supports CMYK effortlessly. In fact PhotoShop was mainly designed for editing CMYK images. To get the same CMYK functionality in GIMP, you need to install it separately.
Supports RAW images. GIMP can only do this if you open it using UFRaw.
Single interface window. This is, in some ways, a disadvantage on multiple monitor set ups. Novice users, however, find it easier to deal with a single interface window. GIMP can support this in two ways. The obvious one is to use GimpShop or GimpPhoto. The built-in way is to choose “Windows → Single Window Mode”.

Final verdict: GIMP doesn’t replace all of PhotoShop’s functionality, but it replaces enough of it to make this software a serious contender. The difference in price, especially considering this is not the only software you’re going to need, is a major factor in favor of GIMP.

The best way may be to start with GIMP, customize it to work like PhotoShop (which is very easy) and then transition to PhotoShop once you find you truly have a need for the additional features.

2. Inkscape vs Illustrator

Adobe illustrator is the market leader in vector graphics, and indeed it has so many powerful features for the professional designer, it probably deserves to be so popular.

Inkscape is very capable too, however. Basically the situation is if you can’t draw something well in Inkscape, you won’t be able to draw it well in Illustrator either.

 Inkscape default interface

Advantages of Inkscape:

Free. You’ll save a lot of money by using Inkscape instead of Illustrator.
Open source. You can inspect the source code, modify it, recompile it, etc. You could even create your own entirely new vector graphics application based on Inkscape’s source code.
Cross-platform. Works on all major operating systems.
Easy to learn and use. Inkscape is a bit simpler than Illustrator, so it is easier to learn.
Imports more image types. This is self-explanatory.
Saves directly to SVG. Illustrator can do this too, but doesn’t do it as well, and you need to select it when you save, or your file will be stored in proprietary AI format. Inkscape defaults to SVG.
Easy object cloning. It’s amazingly easy to clone anything in Inkscape. Not only that, but the latest versions of Inkscape allow you to create tiled clones, so you can quickly create interesting patterns without all the work of manually positioning each tile.
Easy object duplication. What’s the difference between a clone and a duplicate? If you make a change to a cloned object, all of it’s clones will change as well. If you make a change to a duplicated object, only the active copy is changed.

 Adobe Illustrator default interface

Advantages of Illustrator:

Industry standard. Looks good when listed as a skill on your CV.
Supports gradient meshes. It’s not every day you’d be likely to need to make use of a gradient mesh, so whether this point is a deal-breaker depends on the kind of work you do. This advantage is being stripped away as you’re reading this, because the next release of Inkscape is going to include gradient meshes.
Allows more than one stroke color and fill color per object. When you draw a shape in Inkscape, every line of the shape border or path border is continuous and only one color can be used. Illustrator allows you to mix and match.

Final verdict: If you’re any good at drawing, there’s nothing you can create in Illustrator that you can’t create in Inkscape, but Illustrator offers a few extra tools that make the work a bit lighter. You can easily overcome Inkscape’s few limitations, however, so the decision to spend a lot of money on Illustrator needs to be considered carefully.

Before we sign off on Inkscape, there’s just one more myth to bust. Many people declare that Illustrator is better because Inkscape doesn’t do CMYK color. This simply isn’t true. Using a simple plug-in, you can create CMYK output.

3. Scribus vs InDesign

Scribus and InDesign share a common purpose, but that’s about all they share. Both are quite competent at DTP, but InDesign is a far more mature product.

 Scribus interface (image by Nicolas Vérité, CC2.0-SA)

Advantages of Scribus:

Free. You’ll save money using Scribus instead of InDesign.
Open source. Scribus could use some improvement. It’s open source nature allows for that.
Cross-platform. Scribus works on all major operating systems, plus a few more obscure ones.

InDesign interface (image by Mike, CC2.0-ND)

Advantages of InDesign:

More intuitive interface. Most users who have used both find it easier to learn InDesign.
Better text handling. Scribus still has some room for improvement when it comes to editing text. InDesign works perfectly.
Better documentation. If you need help with Scribus, you’ll spend a lot of time on Google and browsing forums. InDesign has mature documentation and plenty of additional support to call upon.

Final verdict: If you need to do a lot of DTP work, InDesign may give you better workflow, so it may be worth the investment. If you only occasionally dabble in DTP, Scribus can do virtually everything InDesign can do, and does it for free.

4. Blender vs Maya

Most graphic designers rarely need to delve into the cruel and punishing world of 3D images, but Blender (free) and Maya (proprietary) are the leading tools in 3D graphics creation and 3D animation.

 Blender interface (image by Dany123, CC3.0-SA)

Advantages of Blender:

Free. Which is amazing, considering how good it is.
Open source. If you want to change something, you don’t have to wait for somebody else to fix it. You can fix it yourself.
Cross-platform. Works on Windows, Mac, Linux.
Built-in game engine. This can be used for any kind of animation, plus simulated physics reactions.
Built in cloth simulator. If you need a flag to flutter in the wind, Blender makes that easy. There’s also a fluid simulator, but that’s not an advantage because Maya has it too.
Many add-ons available free or cheap. There are add-ons to let you easily generate trees, rocks, weeds, debris, roads, cities, people, and so on. Most of these are free or cost little compared to Maya add-ons.
More intuitive modeling system. It may depend slightly on your personal style, but many people who have worked with both find Blender’s modeling system more intuitive.

 Maya interface (image by Mr Ben, CC-3.0SA)

Advantages of Maya:

None.

Final verdict: Blender wins this one really easily, because Maya costs so much and doesn’t deliver anything really special. On the other hand, Blender is free and does deliver a lot. You can do really incredible things with both items of software. Maya is really great, but so is Blender, and the latter just happens to be free.

Something else to think about: on average it might take up to two years to make a feature-length animated film, and if you’re using Maya, you’ll probably spend quite a lot of money just keeping your software and expensive paid add-ons up to date.

So does free graphic design software really stack up?

The answer is a solid maybe. So much depends on what you want to do and what you need to do. What we can say with some certainty is that most of the popular free graphic design software, with the exception of Scribus, is good enough to get you off to a decent start.

The software you use is not what makes you a great designer. It’s how you use the software, your talent, and your attitude to getting the job done that makes all the difference to the quality you can provide to clients.

header image courtesy of tubik

The post How Does Free Graphic Design Software Stack Up? appeared first on Inspired Magazine.

Popular Website Interfaces Reimagined on CodePen

Original Source: http://feedproxy.google.com/~r/1stwebdesigner/~3/ky5d7dICcK4/

Redesigning a popular interface is a great way to improve your skills.

Whether you want to hone your mockup design skills or craft your frontend prowess, a fancy redesign is a solid practice project.

It’s easy to search Dribbble and find tons of website redesigns as static images. But it’s not so easy to find similar redesigns in code.

That’s why I took a dive into CodePen’s archives to find these 11 custom interfaces that reimagine popular sites. You’ll find designs for Twitter, IMDb and even a few other notable websites you might recognize.

Google Search Redesign

See the Pen Google Search (Custom) Redesign #2 by max (@vm187) on CodePen.

The infamous Google search page gets billions of impressions per day. Actually 3.5b per day, to be exact.

So that page needs a design that’s on-point. If you’re redesigning something, there is a bit of room to have fun with it and that’s the idea behind this pen.

It’s a simple Google page redesign focusing just on the search input field. It features a bright, colorful button with drop shadow effects that you’d never see from Google’s design team.

The result is a fun way to reimagine search.

Gmail Application

See the Pen Gmail Application by Kenny (@ispykenny) on CodePen.

Google fans will probably enjoy this reimangined Gmail in a similar vein as the last pen.

But this one features a full Gmail interface – so it’s a little more detailed.

Clicking through the sidebar animations, you’ll notice that they really do animate smoothly. Not to mention the sleek material design color scheme.

If you’re a frequent Gmail user, you may even prefer this redesign over the current style.

Google Branded Redesign

See the Pen Google Redesign by MohamadReza Deylami (@imohamad) on CodePen.

Here’s another Google redesign I wanted to throw in. This one’s a little more detailed with links for Google’s entire set of tools.

This pen by Mohamad Reza Deylami features a redesigned Google logo, altered color scheme and links to all of their different search features.

I think it’s a bit more complex than the current page – so I wouldn’t take it over Google’s design.

What I do like about this redesign is that it’s unique and it stays true to the Google style. Oh and all the code is open source, too.

Twitter UX

See the Pen Twitter UX by Calin (@CalinM) on CodePen.

Twitter has a bunch of UX features spanning their desktop and mobile interfaces. One popular design style is the card interface, which you can see in this pen.

It’s a reimagining of Twitter’s UX with a smaller card design.

This includes a scroll bar along with buttons for editing your profile. And when you scroll down, there are even placeholders for the tweets. How cool!

Modern Twitter Redesign

See the Pen Modern Twitter Redesign by Gibbu (@Gibbu) on CodePen.

Now for something a little more technical, have a peek at this Twitter redesign.

This thing is monstrous and it really does flip the Twitter interface on its head. I actually recommend studying the design in full view to see how it looks in your browser.

I love the menu, love the timeline and really love the simple hover/focus effects. The only thing missing? This isn’t a responsive page.

But in all fairness, Twitter does have a mobile-specific layout aside from the main desktop design. So they handle mobile users differently, too.

FreeCodeCamp Homepage

See the Pen FreeCodeCamp homepage redesign by Giana (@giana) on CodePen.

Developers love FreeCodeCamp for its endless support of new developers and for its friendly approach to charity.

CodePen user Giana must really love the site since they created a full redesign of the FreeCodeCamp homepage.

I can’t really say if it’s a better or worse design. It’s awesome in many ways and also very different. It’s worth a glance if you’re familiar with the original layout.

Spotify Artist Page UI

See the Pen Spotify Artist Page UI by Adam Lowenthal (@alowenthal) on CodePen.

The Spotify web layout is another widely-known interface and Adam Lowenthal took it upon himself to recreate the Spotify artist page.

Most of the features don’t fully work – so you can’t stream music. But the actual page elements are real, so you could copy/paste this code to mix up your own HTML audio player.

Plus, the whole thing is mobile responsive. So that’s nice.

Unsplash Redesign Stuff

See the Pen Unsplash Redesign Stuff by Kyle Shanks (@mavrK) on CodePen.

I can’t say that this redesign of Unsplash is better than the current homepage. But I do think it’s a creative reimagining of how the layout could look focusing on a different structure.

This pen still has the same grid system but developer Kyle Shanks also places a focus on the email capture box and the dropdown navigation menu.

It’s super clean and super easy to rework if you’d like to edit this for your own site.

IMDb Concept

See the Pen Redesign concept IMDB series page by Joanez Andrades (@JoanezAndrades) on CodePen.

Not everything in this IMDb redesign is functional. That’s the downside here.

But the upside is this design really looks spectacular. It’s absolutely phenomenal and would probably work well as a web-app for touchscreens.

Take a peek at the full view to really see how it all comes together on the page.

LinkedIn Redesign

See the Pen LinkedIn Redesign by Nahom Ebssa (@enahom99) on CodePen.

Over the years, LinkedIn has cluttered their layout with so many extra features. I’m really a fan of minimalism and that’s what I see in this redesign by Nahom Ebssa.

Simple colors with an easy-to-use interface. Many elements even borrow ideas from the material design language.

Granted, the layout doesn’t seem 100% finished – but I think it’s a really nice template.

If you want some HTML/CSS/JS practice, maybe fork this one and try adding your own features.

YouTube Redesign

See the Pen YouTube redesign concept by Dino (@dinocam) on CodePen.

For another design that’s not totally done (but still looks amazing), I have to recommend this YouTube redesign.

It really does look a lot cleaner than the modern YouTube homepage. Granted, some of the images won’t load but you still get the gist of the layout. It’s also 100% free of JavaScript, which is pretty awesome.

None of the links or buttons work – so it’s not usable. Still, this is a brilliant attempt to bring YouTube’s design forward with a much more focused UI.


Web Design Concept for National Geographic

Original Source: http://feedproxy.google.com/~r/abduzeedo/~3/WA-MUeAUKs4/84688

Web Design Concept for National Geographic

Web Design Concept for National Geographic

abduzeedo
May 04, 2018

Andriy Bata shared a very stylish web design concept for the National Geographic web site. It features pretty trendy style, with a clear grid system and very minimal. The imagery provided by the topics that National Geographic covers makes things a bit easier. Overall it’s a nice study of web design, but in my opinion it fails on very important aspects, especially accessibility. Some texts feel just too small and with very little contrast from the background. I think any web designer out there should have the duty to create experiences for all and if you take in consideration that the tools and technology allow us to do that, we should not sacrifice function for the form.

Web design concept

 

web design


BeTheme: The WordPress Theme that Follows the Latest Design Trends

Original Source: https://www.sitepoint.com/betheme-the-wordpress-theme-that-follows-the-latest-design-trends/

This article was created in partnership with BAWMedia. Thank you for supporting the partners who make SitePoint possible.

2018 may be one of the greatest years yet for web design and web designers. There are web designers who are looking to stay relevant by keeping up with the latest trends. They certainly have their work cut out for them. After all, it takes some time to get acquainted and comfortable with new trends. It also takes more time to find ways to incorporate them into website designs.

To make things worse, the latest trends have succeeded in raising the competitive bar. They have made the designer's work just that much more difficult.

Fortunately, there is a WordPress theme that has kept up with the latest in design. Here are examples of the 8 most stunning trends. BeTheme has incorporated them into their more than 330 pre-built websites.

8 Creative Design Trends BeTheme has Already Put to Use
Design Trend #1: Illustration & Graphic Art

Custom art is currently all the rage in web design – and it doesn't appear to be going away any time soon. Eye-catching vintage watercolor illustrations have caught on. They bring that sense of nostalgia that makes people feel relaxed and comfortable.

BeSalmon

BeTea2

Notice the use of bold fonts (complete with serifs in the second example). It attracts attention without detracting from the illustrations.

Design Trend #2: Light, Shadow & Smoke

Playing with lights and shadows has always been a popular web design technique. When you add smoke to the mix the design trend takes on a whole new look with a different vibe, especially when it comes to music and dance.

The right mix of light, shadow, and smoke lead to a soft, romantic look:

BeMusician

Or a something a bit more dramatic:

BeHipHop

Or a perfect combination of sultry and classy…

BePole

Design Trend #3: Gradients aka Color Transitions

Gradients are hot. Even hotter than last year's use of bold colors. Gradients, or color transitions, work especially well with pastel colors. When they are allowed to clash with other design trends, the results can be surprising.

BeMusic2

BeApp3

Design Trend #4: 3D “Moving” Stills

Creating a 3D "moving" still can be tough, but when done right it can be a genuine eye-catcher. Maybe it's because the illusion of the movement often attracts us more than movement itself. Here's a pair of examples where you can see the results for yourself – a 3D image that appears to flow.

BeStone

BeDigital

There's so much you can do with images like this. Give them any texture, play with light and shadow, make use of gradients or negative space. 3D moving stills combine nicely with many of the other trends to produce unique results.

Design Trend #5: 2018 Still Life

Still life has been popular for a long time. It's a trend that could likely go on forever, but that doesn't mean it can't be improved upon. The most popular form of modern still life is – you guessed it – 3D.

BeDietitian

You can also use photography (or a 3D-photo combo). Here's a pair of examples that make extraordinary use of white space:

Continue reading %BeTheme: The WordPress Theme that Follows the Latest Design Trends%

Collective #415

Original Source: http://feedproxy.google.com/~r/tympanus/~3/EPZ1NYoTNKE/

C415_warriorjs

Warrior.js

An interactive JavaScript coding game that will put your skills to the test.

Check it out

C415_WP

Our Sponsor
Must Have WordPress Plugins for Designers and Developers

We’ve done the search for you and here are nine of the top plugins on the market that you need to know about.

Check them out

C415_math

Math and front-end: Context is so much more important than degree of difficulty

Chen Hui Jing takes a look at some of the aspects of web development where math can come in handy.

Read it

C415_unicodepatterns

Unicode Patterns

Yuan Chuan explores some amazing Unicode and CSS powered patterns.

Read it

C415_stopwatch

Free Font: Stopwatch

Alex Townsend created this interesting typeface as a typographic experiment.

Get it

C415_morse

Morse Typing Trainer for Gboard

A fun Android web app for learning Morse code on Gboard.

Check it out

C415_designer25

A 25-Step Program for Becoming a Great Designer

Jon Moore shares some great, down-to-earth tips on becoming a better designer.

Read it

C415_logos

Record Label Logos

Reagan Ray’s gigantic collection of record label logos.

Check it out

C415_noise

Leaving Out Particularities

Super cool Perlin Noise demo by Gerard Ferrandez.

Check it out

C415_vue

Learning Vue

In this CSS-Tricks screencast you’ll learn some useful Vue.js coding with Sarah Drasner and Chris Coyier.

Watch it

C415_bulma

Learn Bulma CSS for free

Learn how to build three beautiful websites in less than an hour with Bulma. Read more about it in this article.

Check it out

C415_websites

Make Frontend Shit Again

Sara Vieira’s Hackatron project: a reminder how “fun” websites once were.

Check it out

C415_figmamaterial

Material Design + Figma Styles = Hot

Thomas Lowry took on the challenge to make a Material kit that could leverage soon to be released Figma features.

Read it

C415_click

Google YOLO

An interesting read on clickjacking use cases.

Read it

C415_ScrollHint

ScrollHint

A little JavaScript library to suggest that elements are scrollable horizontally.

Check it out

C415_tiat

Tiat

A simple but performant image organizer that does not create redundant files.

Check it out

C415_fbdata

You Can’t Handle the Truth About Facebook Ads, New Harvard Study Shows

Fantastic read on a very interesting study about ad clicking behavior by Sam Biddle.

Read it

C415_googleNN

Google Duplex: An AI System for Accomplishing Real-World Tasks Over the Phone

Read all about Google Duplex, a new technology for conducting natural conversations to carry out “real world” tasks over the phone.

Read it

C415_eqio

Eqio

A compact alternative to element/container queries by Matt Stow.

Check it out

C415_duo

The Artist Font Duo

A beautiful font duo with extended multilingual support.

Get it

C415_jsconcepts

JavaScript Symbols, Iterators, Generators, Async/Await, and Async Iterators – All Explained Simply

A great explanation of some inter-related JavaScript concepts.

Read it

C415_functional

Conversations with a six-year-old on functional programming

Fantastic read on how Brent Yorgey started to play a functional programming game with his son.

Read it

C415_dark

Learning to See in the Dark

A Tensorflow implementation for processing low-light images, based on end-to-end training of a fully convolutional network.

Check it out

Collective #415 was written by Pedro Botelho and published on Codrops.

Google I/O Developer Roundup: What’s New?

Original Source: https://www.smashingmagazine.com/2018/05/google-io-2018/

Google I/O Developer Roundup: What’s New?

Google I/O Developer Roundup: What’s New?

Rachel Andrew

2018-05-11T12:30:47+02:00
2018-05-14T13:47:25+00:00

The Google I/O keynote opened with an animation asking us to “Make Good Things Together,” and in this article, I’m going to round up some of the things announced in the Keynote and Developer Keynote, that are of interest to Smashing readers. The announcements in the keynote were backed up by sessions during the event, which were recorded. To help you use the things announced, I’ll be linking to the videos of those sessions plus any supporting material I’ve been able to find.

I would love to know which of these announcements you would like to find out more about — please do leave a comment below. Also, if you are an author with experience to share on any of these then why not drop us a line with an outline?

The Keynotes

The main announcements were all covered in the keynote presentations. If you want to watch all of the keynotes, you can find them on YouTube along with some condensed versions:

The main Keynote led by CEO Sundar Pichai (here’s a condensed ten-minute version of the most important points),
The Developer Keynote led by Jason Titus (here’s a five-minute version of the important points covered in the Developer Keynote).

What if there was a web conference without… slides? Meet SmashingConf Toronto 2018 ?? with live sessions exploring how experts work behind the scenes. Dan Mall, Lea Verou, Sara Soueidan, Seb Lee-Delisle and many others. June 26–27. With everything from live designing to live performance audits.

Check the speakers →

SmashingConf Toronto 2018, with Dan Mall, Sara Soueidan, Lea Verou and many others.

Google I/O And The Web

I was attending Google I/O as a Web GDE (Google Developer Expert), and I/O typically has a lot of content which is more of interest to Android Developers. That said, there were plenty of announcements and useful sessions for me.

Slide saying Make the platform more powerful, make web development easier

The Web State of the Union session covered announcements and information regarding Lighthouse, PWAs, Polymer 3.0, Web Assembly and AMP. In addition to the video, you can find a write-up of this session on the Chromium Blog.

What’s New in Chrome DevTools covered all of the new features that are available or coming soon to DevTools.

Progressive Web Apps were a big story through the event, and if you have yet to build your first PWA, the PWA Starter Kit presentation can help you get started using Polymer. To look more deeply into Polymer, you could continue with Web Components and the Polymer Project: Polymer 3.0 and beyond. The Polymer site is now updated with the documentation for Polymer 3.0.

Angular wasn’t left out, watch the What’s New in Angular session for all the details.

Headless Chrome is a subject that has interested me lately, as I’m always looking for interesting ways to automate tasks. In the session The Power of Headless Chrome and Browser Automation, you can find out about using Headless Chrome and Puppeteer. If you are wondering what sort of things you could achieve, there are some examples of things you might like to do on GitHub.

Also, take a look at:

“Building A Seamless Web” by Dru Knox
“Web Performance Made Easy” by Addy Osmani and Ewa Gasperowicz
“Make Your WordPress Site Progressive” by Alberto Medina
“The Future Of The Web Is Immersive” by Brandon Jones
“Build The Future Of The Web With Modern JavaScript” by Mathias Bynens and Sathya Gunasekaran
“Build The Future Of The Web With Web Assembly And More” by Thomas Nattestad

Android Developer News

I’m not an Android developer, but I was surrounded by people who are. I’ve tried to pick out some of the things that seemed most exciting to the crowd. The session, “What’s New In Android,” is a great place to go to find out all of the key announcements. The first of which is the fact that Android P Beta is now available, and many of the features announced will be available as part of that beta. You can check to see if your device is supported by the Beta here.

Android Jetpack is a set of libraries, tools, and architectural guidance to help make it quick and easy to build great Android apps. The IDEs are integrated with Android Studio, and this seems to be an attempt to streamline the developer experience of common tasks. You can find out more information about Android Jetpack in the session video on What’s New In Android Support Library.

The ability to create Actions in Apps is something that is now in Beta and enables developers to create interactions that cross from Voice to displays — be that your watch, phone or the new Smart Screens that will be introduced later this year.

Slices are an interactive snippet of an App UI, introduced in Android P. To find out more, take a look at this I/O Session from which you can learn how to build a slice and have it appear as suggestions in search results.

Watch the session Design Actions for the Google Assistant Beyond Smart Speakers by Sada Zaidi,
Explore the Conversational Design website,
Read more about Actions,
Bookmark the Actions Playlist from Google Developers on YouTube.

Having looked at a few specific announcements for the Web and Android, I’ll now take a look at some of the bigger themes covered at the event and how these might play out for developers.

Audience and stage

7,000 people attended Google I/O

Artificial Intelligence, Augmented Reality, And Machine Learning

As expected, the main keynote as well as the Developer keynote both had a strong AI, AR, and ML theme. This theme is part of many Google products and announcements. Google is leveraging the huge amount of data that they have collected in order to create some incredible products and services, many of which bring with them new concerns on privacy and consent as the digital and real world merge more closely.

Google Photos is getting new AI features which will help you improve your photographs, by giving suggestions as to how to fix brightness or offer suggested rotations.

A new version of Google News will use AI to present to users a range of coverage on stories they are interested in.

One of the demos that achieved a huge round of applause was when Google Lens was demonstrated being pointed at a section of text in a book, and that text was then able to be copied and pasted into the phone.

"What if you could copy and paste stuff from a real world thing into your phone?"
We've never been this excited about copy and paste before. #io18 #googlelens pic.twitter.com/BjOYS3gfUi

— Android Authority (@AndroidAuth) 8. Mai 2018

If you are interested in using AI then you might like to watch the session AIY: Do It Yourself Artificial Intelligence. Also,

Lead designers at Google on “Design, Machine Learning And Creativity,”
“Bringing AI And Machine Learning Innovations To Healthcare” by Lily Peng and Jessica Mega,
“Exploring AR Interaction” by Chris Kelley, Elly Nattinger, and Luca Prasso
“AR Apps: Build, Iterate And Launch” by Tim Psiaki and Tom Salter

Maps

When traveling, I know the all-too-common scenario of coming out of a train station with maps open and having no idea which direction I am facing and which street is which. Google is hoping to solve this issue with augmented reality, bringing street view photographs and directions to the screen to help you know which direction to start walking in.

Google Maps are also taking more of a slice of the area we might already use FourSquare or Yelp for, bring more recommendations based on places we have already visited or reviewed. In addition, a feature I can see myself using when trying to plan post-conference dinners, the ability to create a shortlist of places and share it with a group in order to select where to go. Android Central have an excellent post on all of the new maps features if you want to know more. These features will be available on the Android and iOS versions of the Google Maps app.

For developers, a roundup of the changes to the Maps API can be found in the session Google Maps Platform: Ready For Scale.

Introducing ML Kit

While many of us will find the features powered by Machine Learning useful as consumers of the apps that use them, if you are keen to use machine learning in your apps, then Google is trying to make that easier for you with ML Kit. ML Kit helps you to bring the power of machine learning to your apps with Google APIs. The five ready-to-go APIs are:

Text Recognition
Face Detection
Barcode Scanning
Image Labeling
Landmark Recognition

Two more APIs will be ready in the coming months: A smart reply API allowing you to support contextual messaging replies in your app, and a high-density face contour addition to the face detection API.

You can read more about ML Kit in this Google Developers post Introducing ML Kit and in the session video ML Kit: Machine Learning SDK For Mobile Developers.

Google Duplex

The most talked about demo of the keynote was Google Duplex, with a demo of Google Assistant having a conversation with a restaurant and hairdresser in order to make a reservation and book an appointment. The demo drew gasps from the crowd as the conversation was so natural, the person on the other end of the phone did not recognize they were not talking to a person.

It didn’t take long for people to move from “*That’s cool!*” to “*That’s scary!*” and there are obvious concerns about the ethics of a robot not declaring that it is not a real person when engaging with someone on the phone.

The recordings that were played during the keynote can be found in Ethan Marcotte’s post about the feature, in which he notes that “Duplex was elegantly, intentionally designed to deceive.” Jeremy Keith wisely points out that the people excited to try this technology are not imagining themselves as the person at the end of the phone.

In addition to Duplex, there were a number of announcements around Google Assistant including the ability to have continued conversation, a back-and-forth conversation that doesn’t require saying “Hey, Google” at the beginning of each phrase.

Accessibility

As a layperson, I can’t help but think that many of the things Google is working on could have hugely positive implications in terms of accessibility. Even the controversial Duplex could enable someone who can’t have a voice call to more easily deal with businesses only contactable by phone. One area where Google technology will soon have an impact is with the Android App Google Lookout which will help visually impaired users understand what is around them, by using the phone camera and giving spoken notifications to the user.

There were several sessions bringing a real focus on accessibility at I/O, including the chance for developers to have an accessibility review of their application. For web developers, Rob Dodson’s talk What’s New In Accessibility covers new features of DevTools to help us build more accessible sites, plus the Accessibility Object Model which gives more control over the accessibility of sites. For Android Developers What’s New In Android Accessibility details the features that will be part of Android P. With the focus on AR and VR, there was also a session on what we need to think about in this emerging area of technology: Accessibility For AR And VR.

Linux Apps Are Coming To Chrome OS

An interesting announcement was the fact that Linux Apps will be installable on Chrome OS, making a ChromeBook a far more interesting choice as a developer. According to VentureBeat, Google is using Debian Stretch, so you’ll be able to run apt and install any software there is a Debian package for. This would include things like Git, VS Code, and Android Studio.

Material Design

The material.io website has been updated for the new version of Material Design; the big announcement for that being Theming, which will allow developers using Material to create their own themes making their apps look a little less like a Google property. Gallery will then allow teams to share and collaborate on their designs.

Also announced was the Material Theme Editor which is a plugin for Sketch, making it Mac only. The website does say that it is “currently available for Sketch” so perhaps other versions will appear in due course.

You can find a write-up of how to create a Material theme on the material.io website. The design.google site is also a useful destination for Material and other Google design themes. From the sessions, you can watch:

“Customize Material Components For Your Product” by Richard Fulcher, Rachel Been, and Josh Estelle
“Code Beautiful UI With Flutter And Material Design” by Mary Via and Will Larche
“Build Great Material Design Products Across Platforms” by Jonathan Chung, Nick Butcher, and Will Larche

Is your pattern library up to date today? Alla Kholmatova has just finished a fully fledged book on Design Systems and how to get them right. With common traps, gotchas and the lessons she learned. Hardcover, eBook. Just sayin’.

Table of Contents →

Digital Wellbeing

Announced at the keynote was the new Google Digital Wellbeing site, along with a suite of features in Android P, and also on YouTube aimed at helping people to disconnect from their devices and reduce stress caused by things such as alerts and notifications. You can explore all of the features at wellbeing.google/. Most of these will require Android P, currently in Beta, however, the YouTube features will be part of the Youtube app and therefore available to everyone.

As a developer, it is interesting to think about how we can implement similar features in our own applications, whether for web or mobile applications. Things like combining notifications into one daily alert, as will be enabled on Youtube, could help to prevent users being overloaded by alerts from you, and able to properly engage with them at a scheduled time. It has become easier and easier to constantly be asking our users to look at us, perhaps we should try to instead work with our users to be available when they need us, and quietly hide away when they are doing something else.

For more information on building a more humane technology ecosystem, explore the Center For Humane Technology website.

News Roundup

Every news site has been posting their own reviews of I/O, so I’ll wrap up with some of the best coverage I’ve seen. As an attendee of the event, I felt it was slickly managed, good fun, yet it was very clear that Google has well-rehearsed and clear messages they want to send to the developer communities who create apps and content. Every key announcement in the main keynotes was followed up by sessions diving into the practical details of how to use that technology in development. There was so much being announced and demonstrated that it is impossible to cover everything in this post — or even to have experienced it all at the event. I know that there are several videos on the I/O playlist that I’ll be watching after returning home.

TechCrunch has an excellent roundup, with individual articles on many of the big announcements,
There’s also a coverage of the event from CNET,
The Verge has a story stream of their content reporting on the announcements.

If you were at I/O or following along with the live stream, what announcements were most interesting to you? You can use the comments to share the things I didn’t cover that would be your highlights of the three days.

Smashing Editorial
(il)

The best cheap Apple Pencil deals of 2018

Original Source: http://feedproxy.google.com/~r/CreativeBloq/~3/uMZ3y40-WKo/best-cheap-apple-pencil-deals

Finding a good Apple Pencil deal isn't always easy. Certainly, you’re unlikely to see a cheap Apple Pencil on sale in the Apple Store. But there are savings to be had, if you know where to look.

Apple’s sophisticated digital stylus is perhaps the most amazing consumer stylus ever designed. It’s fantastic to use, with pressure and tilt sensitivity making it quick and easy to sketch ideas, create stunning images, take notes and more. 

However, if you’re already part of the Apple ecosystem, you’ll know that nothing comes cheap. That includes the Apple Pencil, which only comes bundled with the new iPad: if you want one for your iPad Pro you'll need to buy it separately. 

Fortunately, we can help. We’ve compared prices from all over the world to bring you the very best Apple Pencil deals and discounts available right now. 

9 iPad Pro apps that make the most of Apple Pencil
What is the Apple Pencil used for?

Image: Malika Favre and Sarah Clifford for Apple

The Apple Pencil is a versatile digital stylus pen that lets you take notes, sketch ideas, create illustrations and paintings, edit spreadsheets, annotate or mark up documents and more. 

It operates like a traditional pencil, letting you vary line weight, create realistic and subtle shading, and produce a wide range of artistic effects with impressive accuracy. Drawing feels natural, with no lag to ruin the illusion – and setup is incredibly easy. Just pop the cap off to reveal a Lightning connector, and plug it into your iPad Pro. (That's also how you charge it.) 

The Apple Pencil works with a range of art and design iOS apps including Adobe Draw and Sketch, Procreate, Affinity Photo and more.

Related articles:

The 90 best iPad appsApple launches iPad with Pencil supportThe best drawing tablet

Building Mobile Apps Using React Native And WordPress

Original Source: https://www.smashingmagazine.com/2018/05/building-mobile-apps-using-react-native-wordpress/

Building Mobile Apps Using React Native And WordPress

Building Mobile Apps Using React Native And WordPress

Muhammad Muhsin

2018-05-11T15:15:56+02:00
2018-05-14T13:47:25+00:00

As web developers, you might have thought that mobile app development calls for a fresh learning curve with another programming language. Perhaps Java and Swift need to be added to your skill set to hit the ground running with both iOS and Android, and that might bog you down.

But this article has you in for a surprise! We will look at building an e-commerce application for iOS and Android using the WooCommerce platform as our backend. This would be an ideal starting point for anyone willing to get into native cross-platform development.

A Brief History Of Cross-Platform Development

It’s 2011, and we see the beginning of hybrid mobile app development. Frameworks like Apache Cordova, PhoneGap, and Ionic Framework slowly emerge. Everything looks good, and web developers are eagerly coding away mobile apps with their existing knowledge.

However, mobile apps still looked like mobile versions of websites. No native designs like Android’s material design or iOS’s flat look. Navigation worked similar to the web and transitions were not buttery smooth. Users were not satisfied with apps built using the hybrid approach and dreamt of the native experience.

Fast forward to March 2015, and React Native appears on the scene. Developers are able to build truly native cross-platform applications using React, a favorite JavaScript library for many developers. They are now easily able to learn a small library on top of what they know with JavaScript. With this knowledge, developers are now targeting the web, iOS and Android.

Nope, we can’t do any magic tricks, but we have articles, books and webinars featuring techniques we all can use to improve our work. Smashing Members get a seasoned selection of magic front-end tricks — e.g. live designing sessions and perf audits, too. Just sayin’! 😉

Explore Smashing Wizardry →

Smashing Cat, just preparing to do some magic stuff.

Furthermore, changes done to the code during development are loaded onto the testing devices almost instantly! This used to take several minutes when we had native development through other approaches. Developers are able to enjoy the instant feedback they used to love with web development.

React developers are more than happy to be able to use existing patterns they have followed into a new platform altogether. In fact, they are targeting two more platforms with what they already know very well.

This is all good for front-end development. But what choices do we have for back-end technology? Do we still have to learn a new language or framework?

The WordPress REST API

In late 2016, WordPress released the much awaited REST API to its core, and opened the doors for solutions with decoupled backends.

So, if you already have a WordPress and WooCommerce website and wish to retain exactly the same offerings and user profiles across your website and native app, this article is for you!

Assumptions Made In This Article

I will walk you through using your WordPress skill to build a mobile app with a WooCommerce store using React Native. The article assumes:

You are familiar with the different WordPress APIs, at least at a beginner level.
You are familiar with the basics of React.
You have a WordPress development server ready. I use Ubuntu with Apache.
You have an Android or an iOS device to test with Expo.

What We Will Build In This Tutorial

The project we are going to build through this article is a fashion store app. The app will have the following functionalities:

Shop page listing all products,
Single product page with details of the selected item,
‘Add to cart’ feature,
‘Show items in cart’ feature,
‘Remove item from cart’ feature.

This article aims to inspire you to use this project as a starting point to build complex mobile apps using React Native.

Note: For the full application, you can visit my project on Github and clone it.

Getting Started With Our Project

We will begin building the app as per the official React Native documentation. Having installed Node on your development environment, open up the command prompt and type in the following command to install the Create React Native App globally.

npm install -g create-react-native-app

Next, we can create our project

create-react-native-app react-native-woocommerce-store

This will create a new React Native project which we can test with Expo.

Next, we will need to install the Expo app on our mobile device which we want to test. It is available for both iOS and Android.

On having installed the Expo app, we can run npm start on our development machine.

cd react-native-woocommerce-store

npm start

Starting a React Native project through the command line via Expo. (Large preview)

After that, you can scan the QR code through the Expo app or enter the given URL in the app’s search bar. This will run the basic ‘Hello World’ app in the mobile. We can now edit App.js to make instant changes to the app running on the phone.

Alternatively, you can run the app on an emulator. But for brevity and accuracy, we will cover running it on an actual device.

Next, let’s install all the required packages for the app using this command:

npm install -s axios react-native-htmlview react-navigation react-redux redux redux-thunk

Setting Up A WordPress Site

Since this article is about creating a React Native app, we will not go into details about creating a WordPress site. Please refer to this article on how to install WordPress on Ubuntu. As WooCommerce REST API requires HTTPS, please make sure it is set up using Let’s Encrypt. Please refer to this article for a how-to guide.

We are not creating a WordPress installation on localhost since we will be running the app on a mobile device, and also since HTTPS is needed.

Once WordPress and HTTPS are successfully set up, we can install the WooCommerce plugin on the site.

Installing the WooCommerce plugin to our WordPress installation. (Large preview)

After installing and activating the plugin, continue with the WooCommerce store setup by following the wizard. After the wizard is complete, click on ‘Return to dashboard.’

You will be greeted by another prompt.

Adding example products to WooCommerce. (Large preview)

Click on ‘Let’s go‘ to ‘Add example products’. This will save us the time to create our own products to display in the app.

Constants File

To load our store’s products from the WooCommerce REST API, we need the relevant keys in place inside our app. For this purpose, we can have a constans.js file.

First create a folder called ‘src’ and create subfolders inside as follows:

Create the file ‘Constants.js’ within the constans folder. (Large preview)

Now, let’s generate the keys for WooCommerce. In the WordPress dashboard, navigate to WooCommerce → Settings → API → Keys/Apps and click on ‘Add Key.’

Next create a Read Only key with name React Native. Copy over the Consumer Key and Consumer Secret to the constants.js file as follows:

const Constants = {
URL: {
wc: ‘https://woocommerce-store.on-its-way.com/wp-json/wc/v2/’
},
Keys: {
ConsumerKey: ‘CONSUMER_KEY_HERE’,
ConsumerSecret: ‘CONSUMER_SECRET_HERE’
}
}
export default Constants;

Starting With React Navigation

React Navigation is a community solution to navigating between the different screens and is a standalone library. It allows developers to set up the screens of the React Native app with just a few lines of code.

There are different navigation methods within React Navigation:

Stack,
Switch,
Tabs,
Drawer,
and more.

For our Application we will use a combination of StackNavigation and DrawerNavigation to navigate between the different screens. StackNavigation is similar to how browser history works on the web. We are using this since it provides an interface for the header and the header navigation icons. It has push and pop similar to stacks in data structures. Push means we add a new screen to the top of the Navigation Stack. Pop removes a screen from the stack.

The code shows that the StackNavigation, in fact, houses the DrawerNavigation within itself. It also takes properties for the header style and header buttons. We are placing the navigation drawer button to the left and the shopping cart button to the right. The drawer button switches the drawer on and off whereas the cart button takes the user to the shopping cart screen.

const StackNavigation = StackNavigator({
DrawerNavigation: { screen: DrawerNavigation }
}, {
headerMode: ‘float’,
navigationOptions: ({ navigation, screenProps }) => ({
headerStyle: { backgroundColor: ‘#4C3E54’ },
headerTintColor: ‘white’,
headerLeft: drawerButton(navigation),
headerRight: cartButton(navigation, screenProps)
})
});

const drawerButton = (navigation) => (
<Text
style={{ padding: 15, color: ‘white’ }}
onPress={() => {
if (navigation.state.index === 0) {
navigation.navigate(‘DrawerOpen’)
} else {
navigation.navigate(‘DrawerClose’)
}
}
}> (
<Text style={{ padding: 15, color: ‘white’ }}
onPress={() => { navigation.navigate(‘CartPage’) }}
>
<EvilIcons name=”cart” size={30} />
{screenProps.cartCount}
</Text>
);

DrawerNavigation on the other hands provides for the side drawer which will allow us to navigate between Home, Shop, and Cart. The DrawerNavigator lists the different screens that the user can visit, namely Home page, Products page, Product page, and Cart page. It also has a property which will take the Drawer container: the sliding menu which opens up when clicking the hamburger menu.

const DrawerNavigation = DrawerNavigator({
Home: {
screen: HomePage,
navigationOptions: {
title: “RN WC Store”
}
},
Products: {
screen: Products,
navigationOptions: {
title: “Shop”
}
},
Product: {
screen: Product,
navigationOptions: ({ navigation }) => ({
title: navigation.state.params.product.name
}),
},
CartPage: {
screen: CartPage,
navigationOptions: {
title: “Cart”
}
}
}, {
contentComponent: DrawerContainer
});

#

Left: The Home page (homepage.js). Right: The open drawer (DrawerContainer.js).

Injecting The Redux Store To App.js

Since we are using Redux in this app, we have to inject the store into our app. We do this with the help of the Provider component.

const store = configureStore();

class App extends React.Component {
render() {
return (
<Provider store={store}>
<ConnectedApp />
</Provider>
)
}
}

We will then have a ConnectedApp component so that we can have the cart count in the header.

class CA extends React.Component {
render() {
const cart = {
cartCount: this.props.cart.length
}
return (
<StackNavigation screenProps={cart} />
);
}
}

function mapStateToProps(state) {
return {
cart: state.cart
};
}

const ConnectedApp = connect(mapStateToProps, null)(CA);

Redux Store, Actions, And Reducers

In Redux, we have three different parts:

Store
Holds the whole state of your entire application. The only way to change state is to dispatch an action to it.
Actions
A plain object that represents an intention to change the state.
Reducers
A function that accepts a state and an action type and returns a new state.

These three components of Redux help us achieve a predictable state for the entire app. For simplicity, we will look at how the products are fetched and saved in the Redux store.

Is your pattern library up to date today? Alla Kholmatova has just finished a fully fledged book on Design Systems and how to get them right. With common traps, gotchas and the lessons she learned. Hardcover, eBook. Just sayin’.

Table of Contents →

First of all, let’s look at the code for creating the store:

let middleware = [thunk];

export default function configureStore() {
return createStore(
RootReducer,
applyMiddleware(…middleware)
);
}

Next, the products action is responsible for fetching the products from the remote website.

export function getProducts() {
return (dispatch) => {
const url = `${Constants.URL.wc}products?per_page=100&consumer_key=${Constants.Keys.ConsumerKey}&consumer_secret=${Constants.Keys.ConsumerSecret}`

return axios.get(url).then(response => {
dispatch({
type: types.GET_PRODUCTS_SUCCESS,
products: response.data
}
)}).catch(err => {
console.log(err.error);
})
};
}

The products reducer is responsible for returning the payload of data and whether it needs to be modified.

export default function (state = InitialState.products, action) {
switch (action.type) {
case types.GET_PRODUCTS_SUCCESS:
return action.products;
default:
return state;
}
}

Displaying The WooCommerce Shop

The products.js file is our Shop page. It basically displays the list of products from WooCommerce.

class ProductsList extends Component {

componentDidMount() {
this.props.ProductAction.getProducts();
}

_keyExtractor = (item, index) => item.id;

render() {
const { navigate } = this.props.navigation;
const Items = (
<FlatList contentContainerStyle={styles.list} numColumns={2}
data={this.props.products || []}
keyExtractor={this._keyExtractor}
renderItem={
({ item }) => (
<TouchableHighlight style={{ width: ‘50%’ }} onPress={() => navigate(“Product”, { product: item })} underlayColor=”white”>
<View style={styles.view} >
<Image style={styles.image} source={{ uri: item.images[0].src }} />
<Text style={styles.text}>{item.name}</Text>
</View>
</TouchableHighlight>
)
}
/>
);
return (
<ScrollView>
{this.props.products.length ? Items :
<View style={{ alignItems: ‘center’, justifyContent: ‘center’ }}>
<Image style={styles.loader} source={LoadingAnimation} />
</View>
}
</ScrollView>
);
}
}

this.props.ProductAction.getProducts() and this.props.products are possible because of mapStateToProps and mapDispatchToProps.

Products listing screen. (Large preview)

mapStateToProps and mapDispatchToProps

State is the Redux store and Dispatch is the actions we fire. Both of these will be exposed as props in the component.

function mapStateToProps(state) {
return {
products: state.products
};
}
function mapDispatchToProps(dispatch) {
return {
ProductAction: bindActionCreators(ProductAction, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductsList);

Styles

In React, Native styles are generally defined on the same page. It’s similar to CSS, but we use camelCase properties instead of hyphenated properties.

const styles = StyleSheet.create({
list: {
flexDirection: ‘column’
},
view: {
padding: 10
},
loader: {
width: 200,
height: 200,
alignItems: ‘center’,
justifyContent: ‘center’,
},
image: {
width: 150,
height: 150
},
text: {
textAlign: ‘center’,
fontSize: 20,
padding: 5
}
});

Single Product Page

This page contains details of a selected product. It shows the user the name, price, and description of the product. It also has the ‘Add to cart’ function.

Single product page. (Large preview)

Cart Page

This screen shows the list of items in the cart. The action has the functions getCart, addToCart, and removeFromCart. The reducer handles the actions likewise. Identification of actions is done through actionTypes — constants which describe the action that are stored in a separate file.

export const GET_PRODUCTS_SUCCESS = ‘GET_PRODUCTS_SUCCESS’
export const GET_PRODUCTS_FAILED = ‘GET_PRODUCTS_FAILED’;

export const GET_CART_SUCCESS = ‘GET_CART_SUCCESS’;
export const ADD_TO_CART_SUCCESS = ‘ADD_TO_CART_SUCCESS’;
export const REMOVE_FROM_CART_SUCCESS = ‘REMOVE_FROM_CART_SUCCESS’;

This is the code for the CartPage component:

class CartPage extends React.Component {

componentDidMount() {
this.props.CartAction.getCart();
}

_keyExtractor = (item, index) => item.id;

removeItem(item) {
this.props.CartAction.removeFromCart(item);
}

render() {
const { cart } = this.props;
console.log(‘render cart’, cart)

if (cart && cart.length > 0) {
const Items = <FlatList contentContainerStyle={styles.list}
data={cart}
keyExtractor={this._keyExtractor}
renderItem={({ item }) =>
<View style={styles.lineItem} >
<Image style={styles.image} source={{ uri: item.image }} />
<Text style={styles.text}>{item.name}</Text>
<Text style={styles.text}>{item.quantity}</Text>
<TouchableOpacity style={{ marginLeft: ‘auto’ }} onPress={() => this.removeItem(item)}><Entypo name=”cross” size={30} /></TouchableOpacity>
</View>
}
/>;
return (
<View style={styles.container}>
{Items}
</View>
)
} else {
return (
<View style={styles.container}>
<Text>Cart is empty!</Text>
</View>
)
}
}
}

As you can see, we are using a FlatList to iterate through the cart items. It takes in an array and creates a list of items to be displayed on the screen.

#

Left: The cart page when it has items in it. Right: The cart page when it is empty.

Conclusion

You can configure information about the app such as name and icon in the app.json file. The app can be published after npm installing exp.

To sum up:

We now have a decent e-commerce application with React Native;
Expo can be used to run the project on a smartphone;
Existing backend technologies such as WordPress can be used;
Redux can be used for managing the state of the entire app;
Web developers, especially React developers can leverage this knowledge to build bigger apps.

For the full application, you can visit my project on Github and clone it. Feel free to fork it and improve it further. As an exercise, you can continue building more features into the project such as:

Checkout page,
Authentication,
Storing the cart data in AsyncStorage so that closing the app does not clear the cart.

Smashing Editorial
(da, lf, ra, yk, il)

A Strategy Guide To CSS Custom Properties

Original Source: https://www.smashingmagazine.com/2018/05/css-custom-properties-strategy-guide/

A Strategy Guide To CSS Custom Properties

A Strategy Guide To CSS Custom Properties

Michael Riethmuller

2018-05-14T13:30:38+02:00
2018-05-14T13:47:25+00:00

CSS Custom Properties (sometimes known as ‘CSS variables’) are now supported in all modern browsers, and people are starting to use them in production. This is great, but they’re different from variables in preprocessors, and I’ve already seen many examples of people using them without considering what advantages they offer.

Custom properties have a huge potential to change how we write and structure CSS and to a lesser extent, how we use JavaScript to interact with UI components. I’m not going to focus on the syntax and how they work (for that I recommend you read “It’s Time To Start Using Custom Properties”). Instead, I want to take a deeper look at strategies for getting the most out of CSS Custom Properties.

How Are They Similar To Variables In Preprocessors?

Custom Properties are a little bit like variables in preprocessors but have very some important differences. The first and most obvious difference is the syntax.

With SCSS we use a dollar symbol to denote a variable:

$smashing-red: #d33a2c;

In Less we use an @ symbol:

@smashing-red: #d33a2c;

Custom properties follow a similar conventions and use a — prefix:

:root { –smashing-red: #d33a2c; }
.smashing-text {
color: var(–smashing-red);
}

One important difference between custom properties and variables in preprocessors is that custom properties have a different syntax for assigning a value and retrieving that value. When retrieving the value of a custom property we use the var() function.

Nope, we can’t do any magic tricks, but we have articles, books and webinars featuring techniques we all can use to improve our work. Smashing Members get a seasoned selection of magic front-end tricks — e.g. live designing sessions and perf audits, too. Just sayin’! 😉

Explore Smashing Wizardry →

Smashing Cat, just preparing to do some magic stuff.

The next most obvious difference is in the name. They are called ‘custom properties’ because they really are CSS properties. In preprocessors, you can declare and use variables almost anywhere, including outside declaration blocks, in media rules, or even as part of a selector.

$breakpoint: 800px;
$smashing-red: #d33a2c;
$smashing-things: “.smashing-text, .cats”;

@media screen and (min-width: $breakpoint) {
#{$smashing-things} {
color: $smashing-red;
}
}

Most of the examples above would be invalid using custom properties.

Custom properties have the same rules about where they can be used as normal CSS properties. It’s far better to think of them as dynamic properties than variables. That means they can only be used inside a declaration block, or in other words, custom properties are tied to a selector. This can be the :root selector, or any other valid selector.

:root { –smashing-red: #d33a2c; }

@media screen and (min-width: 800px) {
.smashing-text, .cats {
–margin-left: 1em;
}
}

You can retrieve the value of a custom property anywhere you would otherwise use a value in a property declaration. This means they can be used as a single value, as part of a shorthand statement or even inside calc() equations.

.smashing-text, .cats {
color: var(–smashing-red);
margin: 0 var(–margin-horizontal);
padding: calc(var(–margin-horizontal) / 2)
}

However, they cannot be used in media rules, or selectors including :nth-child().

There is probably a lot more you want to know about the syntax and how custom properties work, such as how to use fallback values and can you assign variables to other variables (yes), but this basic introduction should be enough to understand the rest of the concepts in this article. For more information on the specifics of how custom properties work, you can read “It’s Time To Start Using Custom Properties” written by Serg Hospodarets.

Dynamic vs. Static

Cosmetic differences aside, the most significant difference between variables in preprocessors and custom properties is how they are scoped. We can refer to variables as either statically or dynamically scoped. Variables in preprocessors are static whereas custom properties are dynamic.

Where CSS is concerned static means that you can update the value of a variable at different points in the compilation process, but this cannot change the value of the code that came before it.

$background: blue;
.blue {
background: $background;
}
$background: red;
.red {
background: $background;
}

results in:

.blue {
background: blue;
}
.red {
background: red;
}

Once this is rendered to CSS, the variables are gone. This means that we could potentially read an .scss file and determine it’s output without knowing anything about the HTML, browser or other inputs. This is not the case with custom properties.

Preprocessors do have a kind of “block scope” where variables can be temporarily changed inside a selector, function or mixin. This changes the value of a variable inside the block, but it’s still static. This is tied to the block, not the selector. In the example below, the variable $background is changed inside the .example block. It changes back to the initial value outside the block, even if we use the same selector.

$background: red;
.example {
$background: blue;
background: $background;
}

.example {
background: $background;
}

This will result in:

.example {
background: blue;
}
.example {
background: red;
}

Custom properties work differently. Where custom properties are concerned, dynamically scoped means they are subject to inheritance and the cascade. The property is tied to a selector and if the value changes, this affects all matching DOM elements just like any other CSS property.

This is great because you can change the value of a custom property inside a media query, with a pseudo selector such as hover, or even with JavaScript.

a {
–link-color: black;
}
a:hover,
a:focus {
–link-color: tomato;
}
@media screen and (min-width: 600px) {
a {
–link-color: blue;
}
}

a {
color: var(–link-color);
}

We don’t have to change where the custom property is used — we change the value of the custom property with CSS. This means using the same custom property, we can have different values in different places or context on the same page.

Global vs. Local

In addition to being static or dynamic, variables can also be either global or local. If you write JavaScript, you will be familiar with this. Variables can either be applied to everything inside an application, or their scope can be limited to specific functions or blocks of code.

CSS is similar. We have some things that are applied globally and some things that are more local. Brand colors, vertical spacing, and typography are all examples of things you might want to be applied globally and consistently across your website or application. We also have local things. For example, a button component might have a small and large variant. You wouldn’t want the sizes from these buttons to be applied to all input elements or even every element on the page.

This is something we are familiar with in CSS. We’ve developed design systems, naming conventions and JavaScript libraries, all to help with isolating local components and global design elements. Custom properties provide new options for dealing with this old problem.

CSS Custom Properties are by default locally scoped to the specific selectors we apply them to. So they are kinda like local variables. However, custom properties are also inherited, so in many situations they behave like global variables — especially when applied to the :root selector. This means that we need to be thoughtful about how to use them.

So many examples show custom properties being applied to the :root element and although, this fine for a demo, it can result in a messy global scope and unintended issues with inheritance. Luckily, we’ve already learned these lessons.

Global Variables Tend To Be Static

There are a few small exceptions, but generally speaking, most global things in CSS are also static.

Global variables like brand colors, typography and spacing don’t tend to change much from one component to the next. When they do change this tends to be a global rebranding or some other significant change that rarely happens on a mature product. It still makes sense for these things to be variables, they are used in many places, and variables help with consistency. But it doesn’t make sense for them to be dynamic. The value of these variables does not change in any dynamic way.

For this reason, I strongly recommend using preprocessors for global (static) variables. This not only ensures that they are always static, but it visually denotes them within the code. This can make CSS a whole lot more readable and easier to maintain.

Local Static Variables Are OK (Sometimes)

You might think given the strong stance on global variables being static, that by reflection, all local variables might need to be dynamic. While it’s true that local variables do tend to be dynamic, this is nowhere near as strong as the tendency for a global variable to be static.

Locally static variables are perfectly OK in many situations. I use preprocessors variables in component files mostly as a developer convenience.

Consider the classic example of a button component with multiple size variations.

buttons

My scss might look something like this:

$button-sml: 1em;
$button-med: 1.5em;
$button-lrg: 2em;

.btn {
// Visual styles
}

.btn-sml {
font-size: $button-sml;
}

.btn-med {
font-size: $button-med;
}

.btn-lrg {
font-size: $button-lrg;
}

Obviously, this example would make more sense if I was using the variables multiple times or deriving margin and padding values from the size variables. However, the ability to quickly prototype different sizes might be a sufficient reason.

Because most static variables are global, I like to differentiate static variables that are used only inside a component. To do this, you can prefix these variables with the component name, or you could use another prefix such as c-variable-name for component or l-variable-name for local. You can use whatever prefix you want, or you can prefix global variables. Whatever you choose, it’s helpful to differentiate especially if converting an existing codebase to use custom properties.

When To Use Custom Properties

If it is alright to use static variables inside components, when should we use custom properties? Converting existing preprocessor variables to custom properties usually makes little sense. After all, the reason for custom properties is completely different. Custom properties make sense when we have CSS properties that change relative to a condition in the DOM — especially a dynamic condition such as :focus, :hover, media queries or with JavaScript.

I suspect we will always use some form of static variables, although we might need fewer in future, as custom properties offer new ways to organise logic and code. Until then, I think in most situations we are going to be working with a combination of preprocessor variables and custom properties.

It’s helpful to know that we can assign static variables to custom properties. Whether they are global or local, it makes sense in many situations to convert static variables, to locally dynamic custom properties.

Note: Did you know that $var is valid value for a custom property? Recent versions of Sass recognize this, and therefore we need to interpolate variables assigned to custom properties, like this: #{$var}. This tells Sass you want to output the value of the variable, rather than just $var in the stylesheet. This is only needed for situations like custom properties, where a variable names can also be a valid CSS.

If we take the button example above and decide all buttons should use the small variation on mobile devices, regardless of the class applied in the HTML, this is now a more dynamic situation. For this, we should use custom properties.

$button-sml: 1em;
$button-med: 1.5em;
$button-lrg: 2em;

.btn {
–button-size: #{$button-sml};
}

@media screen and (min-width: 600px) {
.btn-med {
–button-size: #{$button-med};
}
.btn-lrg {
–button-size: #{$button-lrg};
}
}

.btn {
font-size: var(–button-size);
}

Here I create a single custom property: –button-size. This custom property is initially scoped to all button elements using the btn class. I then change the value of –button-size above 600px for the classes btn-med and btn-lrg. Finally, I apply this custom property to all button elements in one place.

Don’t Be Too Clever

The dynamic nature of custom properties allows us to create some clever and complicated components.

With the introduction of preprocessors, many of us created libraries with clever abstractions using mixins and custom functions. In limited cases, examples like this are still useful today, but for the most part, the longer I work with preprocessors the fewer features I use. Today, I use preprocessors almost exclusively for static variables.

Custom properties will not (and should not) be immune from this type of experimentation, and I look forward to seeing many clever examples. But in the long run, readable and maintainable code will always win over clever abstractions (at least in production).

I read an excellent article on this topic on the Free Code Camp Medium recently. It was written by Bill Sourour and is called “Don’t Do It At Runtime. Do It At Design Time.” Rather than paraphrasing his arguments, I’ll let you read it.

One key difference between preprocessor variables and custom properties is that custom properties work at runtime. This means things that might have been borderline acceptable, in terms of complexity, with preprocessors might not be a good idea with custom properties.

One example that illustrated this for me recently was this:

:root {
–font-scale: 1.2;
–font-size-1: calc(var(–font-scale) * var(–font-size-2));
–font-size-2: calc(var(–font-scale) * var(–font-size-3));
–font-size-3: calc(var(–font-scale) * var(–font-size-4));
–font-size-4: 1rem;
}

This generates a modular scale. A modular scale is a series of numbers that relate to each other using a ratio. They are often used in web design and development to set font-sizes or spacing.

In this example, each custom property is determined using calc(), by taking the value of the previous custom property and multiplying this by the ratio. Doing this, we can get the next number in the scale.

This means the ratios are calculated at run-time and you can change them by updating only the value of the –font-scale property. For example:

@media screen and (min-width: 800px) {
:root {
–font-scale: 1.33;
}
}

This is clever, concise and much quicker than calculating all the values again should you want to change the scale. It’s also something I would not do in production code.

Although the above example is useful for prototyping, in production, I’d much prefer to see something like this:

:root {
–font-size-1: 1.728rem;
–font-size-2: 1.44rem;
–font-size-3: 1.2em;
–font-size-4: 1em;
}

@media screen and (min-width: 800px) {
:root {
–font-size-1: 2.369rem;
–font-size-2: 1.777rem;
–font-size-3: 1.333rem;
–font-size-4: 1rem;
}
}

Similar to the example in Bill’s article, I find it helpful to see what the actual values are. We read code many more times than we write it and global values such as font scales change infrequently in production.

The above example is still not perfect. It violates the rule from earlier that global values should be static. I’d much prefer to use preprocessor variables and convert them to locally dynamic custom properties using the techniques demonstrated earlier.

It is also important to avoid situations where we go from using one custom property to a different custom property. This can happen when we name properties like this.

Change The Value Not The Variable

Change the value not the variable is one of the most important strategies for using custom properties effectively.

As a general rule, you should never change which custom property is used for any single purpose.
It’s easy to do because this is exactly how we do things with preprocessors, but it makes little sense with custom properties.

In this example, we have two custom properties that are used on an example component. I switch from using the value of –font-size-small to –font-size-large depending on the screen size.

:root {
–font-size-small: 1.2em;
–font-size-large: 2em;
}
.example {
font-size: var(–font-size-small);
}
@media screen and (min-width: 800px) {
.example {
font-size: var(–font-size-large);
}
}

A better way to do this would be to define a single custom property scoped to the component. Then using a media query, or any other selector, change its value.

.example {
–example-font-size: 1.2em;
}
@media screen and (min-width: 800px) {
.example {
–example-font-size: 2em;
}
}

Finally, in a single place, I use the value of this custom property:

.example {
font-size: var(–example-font-size);
}

In this example and others before it, media queries have only been used to change the value of custom properties. You might also notice there is only one place where the var() statement is used, and regular CSS properties are updated.

This separation between variable declarations and property declarations is intentional. There are many reasons for this, but the benefits are most obvious when thinking about responsive design.

Responsive Design With Custom Properties

One of the difficulties with responsive design when it relies heavily on media queries is that the no matter how you organize your CSS, styles relating to a particular component become fragmented across the stylesheet.

It can be very difficult to know what CSS properties are going to change. Still, CSS Custom Properties can help us organize some of the logic related to responsive design and make working with media queries a lot easier.

If It Changes It’s A Variable

Properties that change using media queries are inherently dynamic and custom properties provide the means to express dynamic values in CSS. This means that if you are using a media query to change any CSS property, you should place this value in a custom property.

You can then move this, along with all the media rules, hover states or any dynamic selectors that define how the value changes, to the top of the document.

Separate Logic From Design

When done correctly, separation of logic and design means that media queries are only be used to change the value of custom properties. It means all the logic related to responsive design should be at the top of the document, and wherever we see a var() statement in our CSS, we immediately know that this property that changes. With traditional methods of writing CSS, there was no way of knowing this at a glance.

Many of us got very good at reading and interpreting CSS at a glance while tracking in our head which properties changed in different situations. I’m tired of this, and I don’t want to do this anymore! Custom properties now provide a link between logic and its implementation, so we don’t need to track this, and that is incredibly useful!

The Logic Fold

The idea of declaring variables at the top of a document or function is not a new idea. It’s something we do in most languages, and it’s now something we can do in CSS as well. Writing CSS in this way creates a clear visual distinction between CSS at the top of the document and below. I need a way to differentiate these sections when I talk about them and the idea of a “logic fold” is a metaphor I’ve started using.
Above the fold contains all preprocessor variables and custom properties. This includes all the different values a custom property can have. It should be easy to trace how a custom property changes.

CSS below the fold is straightforward and highly declarative and easy to read. It feels like CSS before media queries and other necessary complexities of modern CSS.

Take a look at a really simple example of a six column flexbox grid system:

.row {
–row-display: block;
}
@media screen and (min-width: 600px) {
.row {
–row-display: flex;
}
}

The –row-display custom property is initially set to block. Above 800px the display mode is set to flex.

Below the fold might look like this:

.row {
display: var(–row-display);
flex-direction: row;
flex-wrap: nowrap;
}
.col-1, .col-2, .col-3,
.col-4, .col-5, .col-6 {
flex-grow: 0;
flex-shrink: 0;
}
.col-1 { flex-basis: 16.66%; }
.col-2 { flex-basis: 33.33%; }
.col-3 { flex-basis: 50%; }
.col-4 { flex-basis: 66.66%; }
.col-5 { flex-basis: 83.33%; }
.col-6 { flex-basis: 100%; }

We immediately know –row-display is a value that changes. Initially, it will be block, so the flex values will be ignored.

This example is fairly simple, but if we expanded it to include a flexible width column that fills the remaining space, it’s likely flex-grow, flex-shrink and flex-basis values would need to be converted to custom properties. You can try this or take a look at a more detailed example here.

Custom Properties For Theming

I’ve mostly argued against using custom properties for global dynamic variables and hopefully implied that attaching custom properties to the :root selector is in many cases considered harmful. But every rule has an exception, and for custom properties, it’s theming.

Limited use of global custom properties can make theming a whole lot easier.

Theming generally refers to letting users customize the UI in some way. This could be something like changing colors on a profile page. Or it might be something more localized. For example, you can choose the color of a note in the Google Keep application.

Google Keep App

Theming usually involves compiling a separate stylesheet to override a default value with user preferences, or compiling a different stylesheet for each user. Both of these can be difficult and have an impact on performance.

With custom properties, we don’t need to compile a different stylesheet; we only need to update the value of properties according to the user’s preferences. Since they are inherited values, if we do this on the root element they can be used anywhere in our application.

Capitalize Global Dynamic Properties

Custom properties are case sensitive and since most custom properties will be local, if you are using global dynamic properties, it can make sense to capitalize them.

:root {
–THEME-COLOR: var(–user-theme-color, #d33a2c);
}

Capitalization of variables often signifies global constants. For us, this is going to signify that the property is set elsewhere in the application and that we should probably not change it locally.

Avoid Directly Setting Global Dynamic Properties

Custom properties accept a fallback value. It can be a useful to avoid directly overwriting the value of a global custom properties and keep user values separate. We can use the fallback value to do this.

The example above sets the value of –THEME-COLOR to the value of –user-theme-color if it exists. If –user-theme-color is not set, the value of #d33a2c will be used. This way, we don’t need to provide a fallback every time we use –THEME-COLOR.

You might expect in the example below that the background will be set to green. However, the value of –user-theme-color has not been set on the root element, so the value of –THEME-COLOR has not changed.

:root {
–THEME-COLOR: var(–user-theme-color, #d33a2c);
}
body {
–user-theme-color: green;
background: var(–THEME-COLOR);
}

Indirectly setting global dynamic properties like this protects them from being overwritten locally and ensures user settings are always inherited from the root element. This is a useful convention to safeguard your theme values and avoid unintended inheritance.

If we do want to expose specific properties to inheritance, we can replace the :root selector with a * selector:

:root {
–THEME-COLOR: var(–user-theme-color, #d33a2c);
}
body {
–user-theme-color: green;
background: var(–THEME-COLOR);
}

Now the value of –THEME-COLOR is recalculated for every element and therefore the local value of –user-theme-color can be used. In other words, the background color in this example will be green.

You can see some more detailed examples of this pattern in the section on Manipulating Color With Custom Properties.

Updating Custom Properties With JavaScript

If you want to set custom properties using JavaScript there is a fairly simple API and it looks like this:

const elm = document.documentElement;
elm.style.setProperty(‘–USER-THEME-COLOR’, ‘tomato’);

Here I’m setting the value of –USER-THEME-COLOR on the document element, or in other words, the :root element where it will be inherited by all elements.

This is not a new API; it’s the same JavaScript method for updating styles on an element. These are inline styles so they will have a higher specificity than regular CSS.

This means it’s easy to apply local customizations:

.note {
–note-color: #eaeaea;
}
.note {
background: var(–note-color);
}

Here I set a default value for –note-color and scope this to the .note component. I keep the variable declaration separate from the property declaration, even in this simple example.

const elm = document.querySelector(‘#note-uid’);
elm.style.setProperty(‘–note-color’, ‘yellow’);

I then target a specific instance of a .note element and change the value of the –note-color custom property for that element only. This will now have higher specificity than the default value.

You can see how this works with this example using React. These user preferences could be saved in local storage or in the case of a larger application perhaps in a database.

Manipulating Color With Custom Properties

In addition to hex values and named colors, CSS has colors function such as rgb() and hsl(). These allow us to specify individual components of a color such as the hue or lightness. Custom properties can be used in conjunction with color functions.

:root {
–hue: 25;
}
body {
background: hsl(var(–hue), 80%, 50%);
}

This is useful, but some of the most widely used features of preprocessors are advanced color functions that allow us to manipulate color using functions like lighten, darken or desaturate:

darken($base-color, 10%);
lighten($base-color, 10%);
desaturate($base-color, 20%);

It would be useful to have some of these features in browsers. They are coming, but until we have native color modification functions in CSS, custom properties could fill some of that gap.

We’ve seen that custom properties can be used inside existing color functions like rgb() and hsl() but they can also be used in calc(). This means that we can convert a real number to a percentage by multiplying it, e.g. calc(50 * 1%) = 50%.

:root {
–lightness: 50;
}
body {
background: hsl(25, 80%, calc(var(–lightness) * 1%));
}

The reason we want to store the lightness value as a real number is so that we can manipulate it with calc before converting it to a percentage. For example, if I want to darken a color by 20%, I can multiply its lightness by 0.8. We can make this a little easier to read by separating the lightness calculation into a locally scoped custom property:

:root {
–lightness: 50;
}
body {
–lightness: calc(var(–lightness * 0.8));
background: hsl(25, 80%, calc(var(–lightness) * 1%));
}

We could even abstract away more of the calculations and create something like color modification function in CSS using custom properties. This example is likely too complex for most practical cases of theming, but it demonstrates the full power of dynamic custom properties.

Simplify Theming

One of the advantages of using custom properties is the ability to simplify theming. The application doesn’t need to be aware of how custom properties are used. Instead, we use JavaScript or server-side code to set the value of custom properties. How these values are used is determined by the stylesheets.

This means once again that we are able to separate logic from design. If you have a technical design team, authors can update stylesheets and decide how to apply custom properties without changing a single line of JavaScript or backend code.

Custom properties also allow as to move some of the complexity of theming into the CSS and this complexity can have a negative impact on the maintainability of your CSS, so remember to keep it simple wherever possible.

Is your pattern library up to date today? Alla Kholmatova has just finished a fully fledged book on Design Systems and how to get them right. With common traps, gotchas and the lessons she learned. Hardcover, eBook. Just sayin’.

Table of Contents →

Using Custom Properties Today

Even if you’re supporting IE10 and 11, you can start using custom properties today. Most of the examples in this article have to do with how we write and structure CSS. The benefits are significant in terms of maintainability, however, most of the examples only reduce what could otherwise be done with more complex code.

I use a tool called postcss-css-variables to convert most of the features of custom properties into a static representation of the same code. Other similar tools ignore custom properties inside media queries or complex selectors treating custom properties much like preprocessor variables.

What these tools cannot do is emulate the runtime features of custom properties. This means no dynamic features like theming or changing properties with JavaScript. This might be OK in many situations. Depending on the situation, UI customization might be considered a progressive enhancement and the default theme could be perfectly acceptable for older browsers.

Loading The Correct Stylesheet

There are many ways you can use postCSS. I use a gulp process to compile separate stylesheets for newer and older browsers. A simplified version of my gulp task looks like this:

import gulp from “gulp”;
import sass from “gulp-sass”;
import postcss from “gulp-postcss”;
import rename from “gulp-rename”;
import cssvariables from “postcss-css-variables”;
import autoprefixer from “autoprefixer”;
import cssnano from “cssnano”;

gulp.task(“css-no-vars”, () =>
gulp
.src(“./src/css/*.scss”)
.pipe(sass().on(“error”, sass.logError))
.pipe(postcss([cssvariables(), cssnano()]))
.pipe(rename({ extname: “.no-vars.css” }))
.pipe(gulp.dest(“./dist/css”))
);

gulp.task(“css”, () =>
gulp
.src(“./src/css/*.scss”)
.pipe(sass().on(“error”, sass.logError))
.pipe(postcss([cssnano()]))
.pipe(rename({ extname: “.css” }))
.pipe(gulp.dest(“./dist/css”))
);

This results in two CSS files: a regular one with custom properties (styles.css) and one for older browsers (styles.no-vars.css). I want IE10 and 11 to be served styles.no-vars.css and other browsers to get the regular CSS file.

Normally, I’d advocate using feature queries but IE11 doesn’t support feature queries and we’ve used custom properties so extensively that serving a different stylesheet makes sense in this case.

Intelligently serving a different stylesheet and avoiding a flash of unstyled content is not a simple task. If you don’t need the dynamic features of custom properties, you could consider serving all browser styles.no-vars.css and using custom properties simply as a development tool.

If you want to take full advantage of all the dynamic features of custom properties, I suggest using a critical CSS technique. Following these techniques, the main stylesheet is loaded asynchronously while the critical CSS is rendered inline. Your page header might look something like this:

<head>
<style> /* inlined critical CSS */ </style>
<script> loadCSS(‘non-critical.css’); </script>
</head>

We can extend this to load either styles.css or styles.no-vars.css depending on whether the browser supports custom properties. We can detect support like this:

if ( window.CSS && CSS.supports(‘color’, ‘var(–test)’) ) {
loadCSS(‘styles.css’);
} else {
loadCSS(‘styles.no-vars.css’);
}

Conclusion

If you’ve been struggling to organize CSS efficiently, have difficulty with responsive components, want to implement client-side theming, or just want to start off on the right foot with custom properties, this guide should tell you everything you need to know.

It comes down to understanding the difference between dynamic and static variables in CSS as well as a few simple rules:

Separate logic from design;
If a CSS property changes, consider using a custom property;
Change the value of custom properties, not which custom property is used;
Global variables are usually static.

If you follow these conventions, you will find that working with custom properties is a whole lot easier than you think. This might even change how you approach CSS in general.

Further Reading

“It’s Time To Start Using Custom Properties,” Serg Hospodarets
A general introduction to the syntax and the features of custom properties.
“Pragmatic, Practical, And Progressive Theming With Custom Properties,” Harry Roberts
More useful information on theming.
Custom Properties Collection, Mike Riethmuller on CodePen
A number of different examples you can experiment with.

Smashing Editorial
(ra, yk, il)

10 Sleek Apple-Style Code Projects From CodePen

Original Source: http://feedproxy.google.com/~r/1stwebdesigner/~3/v91bae7rM8Y/

Apple is well-known for their incredible design prowess and easy-to-use products. Their technology is a designer’s best friend, so it’s no surprise that we often follow in their footsteps.

It’s also why you can find so many re-creations of Apple’s style on the web. Use the code snippets in this collection for both inspiration and to further your learning.

Menu Redesign

See the Pen Apple menu redesign by Daniel Gooß (@daniel_gooss) on CodePen.

The Apple.com menu is well known by even the youngest web designers. It’s been around for years and has always had such a unique style.

This snippet takes the Apple navigation menu and restyles it using CSS3.

The design is mostly the same, but it includes some different hover features and a custom search menu. But since this is a demo, the links don’t actually work. You’d have to do some editing on this one to make it fully functional.

Messages Waiting Animation

See the Pen Apple Messages “Waiting” Animation by Maxwell Antonucci (@max1128) on CodePen.

Anyone who’s used the Apple messaging app should be familiar with the speech bubble icon. It pops up whenever someone is typing and it’s got a pretty slick animation.

Developer Maxwell Antonucci rebuilt this animation in full with just pure HTML and CSS. You can see the final result in this pen.

Note that this does use Pug for HTML compiling and Sass instead of CSS. But you can always compile down if you can’t read those frameworks.

Either way, this is a brilliant snippet for learning how to design animated graphics using CSS.

Apple-Style Mobile Menu

See the Pen Apple style mobile menu by Andy Leverenz (@justalever) on CodePen.

Beyond the main desktop navigation is Apple’s mobile responsive menu.

This uses the typical hamburger icon and it’s found on most all devices. If you want to re-create this in HTML5, have a look at this free snippet written by Andy Leverenz.

If you click the hamburger icon you get a neat little animation effect, plus the menu actually slides down onto the page. How cool is that!

iOS iMessage in HTML5

See the Pen iOS9 iMessage Responsive HTML5 by Jojo Jonah old (@jojojonahold) on CodePen.

Earlier I mentioned the speech bubble animation from Apple’s messenger app. But with this snippet you can actually build the entire iMessage mobile app using HTML5 and some raw JavaScript.

All of the JS code runs on jQuery – so it’s super easy to edit. Not to mention that the final demo is so darn sleek and really does feel like the real iMessage app.

While I can’t imagine that this would be useful outside of a practice project, it’s still fun to play with.

MacOS + Browser

See the Pen MacOS + Browser by Liam (@Lierrmm) on CodePen.

Speaking of fun practice projects: get a load of this one replicating a full MacOS dashboard in your browser.

You can hover the dock icons to get that traditional Apple animation, or even click the Chrome app icon to open up a mock browser window.

And somehow this pen only uses 55 lines of JavaScript to get it all working.

This is definitely a sweet project that you’ll really appreciate in full view.

Apple Watch Radial Chart

See the Pen Apple Watch Radial Chart by Mark (@xna2) on CodePen.

Apple’s smartwatch broke new ground in the tech space. It also created a whole new interface for consumers to learn.

If you like the Apple Watch animations, then have a look at this snippet on CodePen. It features a custom animated watch face with the radial chart design.

These are fairly common features with many Watch apps, but you never see them in the browser. Well, until now.

Apple Style Toggle

See the Pen Apple Style Toggle by Adrien Bachmann (@AdrienBachmann) on CodePen.

Ah, the classic on/off switch. This first gained popularity thanks to iOS and it really stuck around thanks to Apple’s original design.

In this pen by Adrien Bachmann, you’ll find a basic switch design with HTML/CSS code. It runs completely free of any JavaScript, which is a huge accomplishment by itself.

Not to mention that this snippet is clean and truly does match the Apple-style of animation. You can change the size, color and animation style with ease.

It’s a brilliant way to bring some Apple design into your own web project.

Pure CSS Apple Keyboard

See the Pen Re: Apple Keyboard in pure CSS. by Joey Anuff (@januff) on CodePen.

While this snippet may not be as useful on a real website, it’s certainly a fun project to study.

Developer Joey Anuff created a full CSS-only keyboard modeled after the Apple keyboard.

It does use some JavaScript to support click events dynamically. So you could delete the JS and still have the exact same keyboard in your browser.

This was designed as part of a CSS coding challenge and I have to say that Joey hit this one out of the park.

Search Boxes

See the Pen Search Box inspired by apple by M. Mulia Maulana (@molenmaulana) on CodePen.

We’ve all seen the Apple search box on their main website and in the mobile App Store. It’s got a common theme with rounded corners and a single magnifying glass icon.

This snippet on CodePen recreated the Apple search bar in full.

You’ll notice that there’s actually a couple variations here: a light one and a dark one. These stand out on their own and you can use them to blend into practically any website.

History of Apple.com’s Navbar

See the Pen The History of Apple.com’s Nav Bar in CSS by DBM (@dbm) on CodePen.

This last one is quite a doozy and a fun trip down memory lane.

Take a look at this pen and scroll through some of the designs. You’ll find a huge compilation of every Apple navigation menu dating back to the late 90s.

So many designs, so many crazy gradients. All from one tech company that has left quite a mark on the design space.