Tag: kranthi

Karen McGrane on Content: Windows on the Web

You have five minutes while waiting for a friend to meet you for lunch, so you find yourself shopping for a new pair of shoes. When your friend arrives, you put the phone away, but leave the web page open to help you remember what you found when you get home.

While you’re at work, you read a restaurant review for a new place you think sounds tasty. Come dinnertime, you grab your phone to pull up the address and location.

One night on your tablet, you’re browsing articles for a report you’re writing at work. Back at your desk the next day, you struggle in vain to remember what you searched for to find those articles. Why can’t you find them again?

Sound familiar? If you’re like most people, it probably does. Research from Google (PDF) shows that 90 percent of people start a task using one device, then pick it up later on another device—most commonly, people start a task on smartphone, and then complete it on the desktop. As you might expect, people regularly do this kind of device switching for the most common activities, like browsing the internet (81 percent) or social networking (72 percent). Certain categories like retail (67 percent), financial services (46 percent), and travel (43 percent) also seem to support this kind of sequential use of different devices.

Dual-screen or multi-screen use of devices gets a lot of attention, but we tend to focus on simultaneous usage—say, using tablets or smartphones while watching TV. Publishers, advertisers, and social networks are all actively trying to figure out how to deliver a good experience to users as they shift their attention between two screens at the same time. Sequential usage is every bit as common, but we rarely acknowledge this behavior or try to optimize for this experience.

When people start a task on one device and then complete it on another, they don’t want different content or less content, tailored for the device. They want the same content, presented so they can find it, navigate it, and read it. They imagine that their devices are different-sized windows on the same content, not entirely different containers.

What should we do to provide a good experience for users who want to complete the same task across more than one device?

Content parity

Let’s make device-switching the final nail in the coffin for the argument that mobile websites should offer a subset of the content on the “real” website. Everyone’s had the frustrating experience of trying to find content they’ve seen on the desktop that isn’t accessible from a phone. But the reverse is also a problem: users who start a task from a smartphone during a bit of free time shouldn’t be cut off from options they’d find back at their desktop.

Consistent navigation labels

When picking up a task on a second device, about half of users say they navigate directly to the website to find the desired information again. Users who are trying to locate the same information across a mobile site (or app) and a desktop site can’t rely on the same visual and spatial cues to help them find what they’re looking for. As much as possible, make it easy for them by keeping navigation categories and hierarchy exactly the same. There aren’t that many cases where we truly need to provide different navigation options on mobile. Most desktop navigation systems have been extensively tested—we know those categories and labels work, so keep them consistent.

Consistent search

About 60 percent of users say they’d use search to continue a task on another device. Businesses wondering whether “mobile SEO” is necessary should keep in mind that user tasks and goals don’t necessarily change based on the device—in fact, it’s often the identical user searching for the exact information that very same day. It’s frustrating to get totally different results from different devices when you know what you’re looking for.

Handy tools

Users have taught themselves tricks to make their transition between devices go more smoothly—about half of users report that they send themselves a link. Sites that don’t offer consistent URLs are guaranteed to frustrate users, sending them off on a quest to figure out where that link lives. Responsive design would solve this problem, but so would tools that explicitly allow users to save their progress when logged in, or email a link to the desktop or mobile version of a page.

Improved analytics

Mobile analytics is still in the dark ages. Tracking users between devices is challenging—or impossible—which means businesses don’t have a clear picture of how this kind of multi-device usage is affecting their sales. While true multi-channel analytics may be a ways off, organizations can’t afford to ignore this behavior. Don’t wait for more data to “prove” that customers are moving between devices to complete a task. Customers are already doing it.

It’s time to stop imagining that smartphones, tablets, and desktops are containers that each hold their own content, optimized for a particular browsing or reading experience. Users don’t think of it that way. Instead, users imagine that each device is its own window onto the web.


Karen McGrane on Content: Windows on the Web

You have five minutes while waiting for a friend to meet you for lunch, so you find yourself shopping for a new pair of shoes. When your friend arrives, you put the phone away, but leave the web page open to help you remember what you found when you get home.

While you’re at work, you read a restaurant review for a new place you think sounds tasty. Come dinnertime, you grab your phone to pull up the address and location.

One night on your tablet, you’re browsing articles for a report you’re writing at work. Back at your desk the next day, you struggle in vain to remember what you searched for to find those articles. Why can’t you find them again?

Sound familiar? If you’re like most people, it probably does. Research from Google (PDF) shows that 90 percent of people start a task using one device, then pick it up later on another device—most commonly, people start a task on smartphone, and then complete it on the desktop. As you might expect, people regularly do this kind of device switching for the most common activities, like browsing the internet (81 percent) or social networking (72 percent). Certain categories like retail (67 percent), financial services (46 percent), and travel (43 percent) also seem to support this kind of sequential use of different devices.

Dual-screen or multi-screen use of devices gets a lot of attention, but we tend to focus on simultaneous usage—say, using tablets or smartphones while watching TV. Publishers, advertisers, and social networks are all actively trying to figure out how to deliver a good experience to users as they shift their attention between two screens at the same time. Sequential usage is every bit as common, but we rarely acknowledge this behavior or try to optimize for this experience.

When people start a task on one device and then complete it on another, they don’t want different content or less content, tailored for the device. They want the same content, presented so they can find it, navigate it, and read it. They imagine that their devices are different-sized windows on the same content, not entirely different containers.

What should we do to provide a good experience for users who want to complete the same task across more than one device?

Content parity

Let’s make device-switching the final nail in the coffin for the argument that mobile websites should offer a subset of the content on the “real” website. Everyone’s had the frustrating experience of trying to find content they’ve seen on the desktop that isn’t accessible from a phone. But the reverse is also a problem: users who start a task from a smartphone during a bit of free time shouldn’t be cut off from options they’d find back at their desktop.

Consistent navigation labels

When picking up a task on a second device, about half of users say they navigate directly to the website to find the desired information again. Users who are trying to locate the same information across a mobile site (or app) and a desktop site can’t rely on the same visual and spatial cues to help them find what they’re looking for. As much as possible, make it easy for them by keeping navigation categories and hierarchy exactly the same. There aren’t that many cases where we truly need to provide different navigation options on mobile. Most desktop navigation systems have been extensively tested—we know those categories and labels work, so keep them consistent.

Consistent search

About 60 percent of users say they’d use search to continue a task on another device. Businesses wondering whether “mobile SEO” is necessary should keep in mind that user tasks and goals don’t necessarily change based on the device—in fact, it’s often the identical user searching for the exact information that very same day. It’s frustrating to get totally different results from different devices when you know what you’re looking for.

Handy tools

Users have taught themselves tricks to make their transition between devices go more smoothly—about half of users report that they send themselves a link. Sites that don’t offer consistent URLs are guaranteed to frustrate users, sending them off on a quest to figure out where that link lives. Responsive design would solve this problem, but so would tools that explicitly allow users to save their progress when logged in, or email a link to the desktop or mobile version of a page.

Improved analytics

Mobile analytics is still in the dark ages. Tracking users between devices is challenging—or impossible—which means businesses don’t have a clear picture of how this kind of multi-device usage is affecting their sales. While true multi-channel analytics may be a ways off, organizations can’t afford to ignore this behavior. Don’t wait for more data to “prove” that customers are moving between devices to complete a task. Customers are already doing it.

It’s time to stop imagining that smartphones, tablets, and desktops are containers that each hold their own content, optimized for a particular browsing or reading experience. Users don’t think of it that way. Instead, users imagine that each device is its own window onto the web.


Freelancers, Stop Charging Hourly Rates: How To Guarantee Your Income With Agile Billing


  

For most creative professionals, this story is a familiar one: A client reaches out to you. They need a name, or a logo, or a website, or an app. Actually, they need it all together, and they need it all in a month — well, maybe a month and a half. The initial meetings go well, and they get you a signed contract and a deposit ASAP. You’re ready to start, and your schedule is clear for the next six weeks. And then you get the call.

“We won’t have the content you requested ready for another month.”

“Oh no,” you think. You were actually counting on that second half to pay your rent next month.

Take Control Of Your Finances

You may not be a sole proprietor. Perhaps you run a small boutique firm, or a large ad agency. Even if that’s the case, we all have similar problems: how do we pay our fixed expenses without knowing for sure when we’ll get paid by our clients?

Cash flow is the single most important thing for your business. Without money to pay rent and bills, the business will quickly spiral into Chapter 11. And if you’re a sole proprietor, the stakes are even higher: getting evicted from your office for a late payment is one thing, but if your business is run from a home office, you face the very real prospect of being homeless.

How We Usually Deal With The Cash Flow Problem

The most common way of dealing with uncertain revenue is to start with a lot of money in the bank, or enough credit to take out a loan if necessary. Angel investors, friends and family can help with the former. As designers and developers, we can also create things that bring us passive revenue, although that can become a full-time job in itself — and not necessarily a lucrative one.

Different billing practices require different approaches to ensure cash flow. Some of us charge hourly, while others do fixed per-project fees. The former need to estimate as accurately as possible in order to book enough hours to pay the bills, and some of them end up “churning,” or billing extra hours even if no substantial work is done. The latter must base their estimates on the assumption that every job will take the maximum amount of time possible, and try to work as efficiently as possible.

There’s a serious problem with both of these approaches, however: jobs almost always occupy more of our schedule than we expected.

Delays Cost Money

If the client says they’ll get something to us by Monday, more often than not it will arrive Wednesday, or Friday, or maybe even the following Monday. People are imperfect, and unsurprisingly, our clients have dozens of concerns in addition to our work for them.

We normally deal with this by agreeing to delay the date of the final product by an equivalent number of working days. But what happens when something gets delayed for a month, or two months, or six? We can’t reserve our time for one client indefinitely.

Unfortunately, most work-for-hire contracts do not contain explicit protections against client delays. The AIGA’s “Standard Form of Agreement for Design Services” notes this, but offers little in the way of guidance [emphasis is mine]:

“The danger for you as a businessperson is that an unexpected delay could mean that you’re temporarily unable to produce billable hours. To offset this risk, some creative firms attempt to charge a delay penalty or a restart fee. You may want to raise this issue as a negotiating point. However, most clients are not very receptive to the idea.”

Clients are understandably less than thrilled at the idea of paying to stop work. But that doesn’t mean we can’t protect ourselves against this risk while being up front and fair with our clients.

How To Negotiate A Better Contract

Contract negotiation is extremely difficult. Successful negotiation requires both keen insight into the other party’s needs and desires, as well as an understanding of all of the options available. The best negotiators are also experts at “logrolling“, i.e. trading assets in a negotiation in order to create more value for both parties.

Your initial discussion with a client will set the tone for all of your future negotiations. These talks will inevitably converge on one of two questions.

1. We Want X. How Much Will It Cost?

Anyone who’s ever used a home repair service will tell you to bring in a few people to get estimates before deciding on a contractor. Because we work in a service industry, we should expect the same treatment:

“How much for a website?”

“…What about just a logo?”

Most of our clients have no idea what to spend, for the same reason that we have no idea what to spend on a new roof: we’ve never built a house ourselves. Estimating construction costs is not in our skill set. These questions are the client’s way of sussing out our cost structure.

2. We Have $X. What Can We Get?

In government organizations and academic institutions, money is often earmarked before anyone knows what it will be spent on. Budgets are set aside for “IT”, “marketing” or “advertising”, and the client will have a price ceiling. This doesn’t mean they won’t try to get the best deal — just that they have a limit to their budget that may be less than you’re willing to accept.

Both of the questions above are based on the assumption that creative work can be delivered at a fixed cost. But in practice, each job is a unique problem and takes a variable amount of time to solve. What if, rather than pretending we know exactly what each job will cost, we embraced uncertainty and moved on?

Changing The Conversation

A wise man once said, “If you don’t like what’s being said, change the conversation.” In order for us to protect ourselves and our clients from the inevitable project delays, it helps to finish the initial consultation with a brief chat about our “terms of service.”

Below are my terms for mobile software development. They may inspire you to change your own contract. But whatever your terms look like, make sure they are clear and that you apply them consistently. Writing a Plain English explainer can help quite a bit with this.

Agile Billing Cycles

Instead of worrying about working enough hours or booking enough fixed-bid assignments for the year to pay our bills, we can choose to bill on a weekly, bi-weekly or monthly cycle. The system is based on scrum sprints: two- or four-week blocks of work during which a predetermined set of software features are implemented.

Agile billing addresses the concerns of both clients. Those with a fixed budget know they’ll get all the work their money can buy, and those without one know they won’t pay for more work than necessary. And when a client asks “How much?,” you can give them a range based on how many cycles a project of that size normally takes. If they need a firm number, you’ll need to work out a list of user stories or wireframes with them to determine a fuzzy estimate of how many sprints will be necessary (I use Pivotal Tracker for this).

Cycles are scheduled in much the same way as a magazine ad or sponsorship: weeks are blocked out and purchased in advance. During each cycle, we set aside a certain number of hours per day, part time, during which we make ourselves available to the client. It’s best to keep this to around four to five hours per day, which allows for both administrative overhead and a slight overlap between clients in case a job takes longer than expected. Explicitly limiting availability also prevents last-minute “marathon” sessions, which detract from the end product (and our sanity).

The 20- to 25-hour work week has another important benefit: it enables us to serve a limited number of additional clients on monthly retainers with a much lower time commitment. If a client is unsure about their start date, we can offer to add them to our monthly schedule until they figure it out.

Calling “Time Out”

There’s a big challenge when working on time-based billing cycles, however: clients often shy away from them, because if things take longer than expected, they end up paying for the difference.

Fortunately, we can address their concerns while protecting ourselves from too much exposure. We can allow the client to place a temporary stop-work order one day per week if something on their end takes longer than expected, and then we add those days to the end of the contract if necessary to complete work. This ensures that the client doesn’t shoulder any extra cost in the event of reasonable delays, while protecting our schedule from too much overlap.

Holds, Cancellations and Uncertain Start Dates

Sometimes a project gets cancelled or put on hold. In a “half-up-front, half-on-completion” scenario, mid-project cancellations can cause considerable friction if they happen early and the client feels they are owed some portion of the deposit back.

Freelancers, Stop Charging Hourly And Guarantee Your Income With Agile Billing
Image credits: The Oatmeal.

Agile billing deals with this by allowing clients to cancel a cycle in advance with a variable kill fee depending on how much notice they give. For example, one might allow a client to cancel a two-week cycle one week in advance at a cost of 25%, or up to three days in advance by paying 50%.

In addition, sometimes clients know what they want but aren’t sure exactly when they’ll be able to begin. In these cases, rather than provide free consulting services while they figure out how to proceed, we can offer to add them to our monthly retainer schedule and, in the meantime, assist them in the process with a smaller, more flexible time commitment.

How Much Per Week?

How much you charge per week will depend on multiple factors, including what the market will bear, your own costs, and what your competitors charge for similar services.

How Much Do You Want To Make?

While you should never compete solely on price, talk to a few of your colleagues who freelance to get a sense of what they bill clients. Multiply their hourly rate by around 1000 billable hours per year to get a sense of how much a typical freelance professional in your area bills per annum if they’re booked solid. (If you’re not a sole proprietor, multiply your colleagues’ agency rates accordingly.)

Once you have some realistic figures for comparison, decide how much profit you want to make per year, add your expenses, multiply the sum by 1.5 to account for holidays and low seasons, and divide by 50 to get your weekly rate. If you find that the hourly rate works out to double that of your colleagues’, you may need to revisit your salary expectations or slash some of your expenses.

Closing Thoughts

Most of us are naturally shy about discussing money. But we are professionals, and we merit the same level of financial stability as any other professional. Don’t be afraid to ask for a reasonable billing agreement that guarantees cash flow for you. Your clients, your business and your users will be better off because of it.

Other Resources

  • Design Is a Job, Mike Monteiro
    Monteiro breaks down budgeting, client relations and professional conduct in a well-written, acerbic tract on the business of design.
  • Negotiation Genius, Deepak Malhotra and Max Bazerman
    Two Harvard professors draw on decades of behavioral research and examples to explain the logic behind negotiation strategy.
  • Agile Software Development: A Gentle Introduction,” Don Wells
    A brief introduction to the agile process. While normally associated with software development, agile project management works well in any profession where people deal regularly with uncertainty.
  • Getting Real About Agile Design,” Cennydd Bowles
    Agile isn’t just for developers. This article on A List Apart explains why.
  • Agile Estimating and Planning, Mike Cohn
    Cohn quite literally wrote the book on agile planning for software development.
  • Agile Budgeting: Cash Is King” Jeff Magnusson
    Agile billing’s bespectacled, mathlete cousin, agile budgeting, enables you to keep a rolling estimate of expenses for the next few months, instead of sticking to a monthly or yearly budget.
  • 10 Contracts for Your Next Agile Software Project,” Peter Stevens
    An extended list of the different types of service agreements available. While this article presents them in the context of software, they apply equally to any service industry.
  • How I Went From $100-an-Hour Programming To $X0,000-a-Week Consulting,” Patrick McKenzie
    A good, if incomplete, guide to moving towards higher-paid consulting on a monthly retainer.

(il) (al)


© Benjamin Jackson for Smashing Magazine, 2013.


Coding Q&A: CSS Performance, Debugging, Naming Conventions


  

Howdy folks! Welcome to another round of Smashing Magazine CSS Q&A — the final one, as of now. One more time, we’ll answer the best questions which you sent us about CSS.

It was a great experience to run this Q&A with you — thanks a lot for sharing all your questions with us! We hope we answered them at the best possible, and we’ll surely be back with new and exciting Q&A rounds in the future. Enjoy Chris’ last round on CSS performance, best practices on CSS class naming, and more!

CSS Performance

Vitaly asks:

“Could you recommend some rules of thumb or general tips on how to improve the performance of CSS? What are your general thoughts on the performance issues of CSS? Would you recommend the tips from Jon Rohan’s talk?”

Most of the time, I don’t think you should even bother thinking about the performance of your CSS. However, you should absolutely be thinking about the overall performance of your website.

The first thing to check is your website’s response time. You’ll see that is the very first thing in the “Network� tab of Chrome’s Developer Tools. If that’s, say, a second or more, that’s pretty slow, and you should work to get that down. That means server-side caching, faster servers, more efficient servers or more servers.


CodePen rocks a respectable 216 millisecond response time.

Usually, that’s not the problem with slow websites. That’s the 20% in the 80/20 rule. The other 80% is front-end-related stuff.

In the vast majority of situations, doing any of the following things would take less effort and have a far greater impact on performance than CSS optimizations:

  • Remove one resource (JavaScript file, CSS file or image) from the page (i.e. concatenate them).
  • Ensure that the resources are compressed and Gzip’ed.
  • Ensure that your assets have expires headers that are set far out.
  • Host assets on a content delivery network (CDN).

You can learn more about these things in this slide deck that I’ve put together.

If you’re already doing all of these things and you’re still having problems, that’s where Jon Rohan’s tips can help. Simpler HTML and simpler CSS selectors can make a difference in page-rendering speed.

I just wouldn’t expect huge gains on an “average� website. Remember that for the GitHub “dif� pages in question here, the developers were able to remove thousands and thousands of elements and simplify kinda nasty selectors (such as tag-qualified classes) to achieve their 37% increase in rendering speed. Most of us aren’t in that position.

Naming Classes

Christoph Rumpel asks:

“I would love to hear your opinion and some best practices on CSS class naming. Do you use BEM styles, or do you have your own convention? I am now looking for the best way to keep my CSS code simple, performant and reusable. Please let me know your thoughts on that topic and especially on how you would name nested containers and on what to consider when using selectors.”

I’ve just heard the saying, “There are only two hard things in computer science: cache invalidation and naming things.� Apparently it’s a quote by Phil Karlton that has been turned into an adage. By “naming things� is meant that moment when it’s up to you to choose a name for something. Any name would technically work, but a poorly chosen name will cause confusion and likely haunt your project moving forward. A good name will make for more understandable code and make things easier for all.

HTML class names (yes, we’re supposed to call them HTML classes, not CSS classes) are absolutely one of those things with which naming is important. It’s commonly taught that a class name like leftSidebar or bigRed is bad because it describes the desired look (which could change), rather than the content it contains (which is less likely to).

For myself, I just do my best to describe the content it contains. The best scenario is one in which I’ve identified a pattern and then named that pattern. Then I choose the most semantic element possible to go with the content and roll with it. For instance, a row of icons with numbers beside them might become class="stats". Here are a couple of classes from my currently open project:

<section class="pen-grid group">

<div class="single-pen">

<header class="collection-header">

<img class="user-avatar">

<span class="views">

These have served me well so far. I can understand what these elements are from either the HTML or the CSS.

Regarding wrappers, if a wrapper is needed solely for design reasons, I’ll often use a div (which has no semantic meaning) and apply -wrap to whatever other class name makes sense, so that I know it’s purely for design. No shame in that, if you ask me.

Debugging Preprocessed CSS

Andrea Verlicchi asks:

“I’ve read you’re a great fan of Sass/SCSS, like me. But most colleagues don’t use it because they are concerned about debugging the page, meaning they can’t just inspect the page and easily get the line of CSS where the rules are declared. How would you answer that concern?”

The way this pans out in my life is this: it doesn’t matter. My CSS structure is so organized and I know my text editor well enough that I can quickly jump to the CSS that I need without the help of line numbers in the developer tools.

However, I can understand that not all situations are like this. Seeing line numbers might be especially helpful when working with less familiar code or with code that you haven’t written. You’ll be happy to know that Sass supports source maps, and recent versions of Chrome support source maps, so you’ll be matching up line numbers in no time. If you use Compass, add this to your config.rb file:

sass_options = { :debug_info => true }

Now you’ll get proper line-number mapping:

source-maps-on

If you’re still on Firebug, then FireSass is essentially the same.

Staying Up To Date

Rouzbeh Sarrafieh asks:

“How does a novice/intermediate developer such as myself, who only does HTML and CSS and uses jQuery plugins, not get overwhelmed with all of the new things constantly being popularized and used so widely these days? From Gzip’ing and minifying CSS to using GitHub, CodePen and Sass and optimizing for all of the new resolutions and screen sizes with media queries, while implementing best practice techniques that seem to be changing at such a rapid pace — it all seems like so much to learn without having the time when you have a full-time job.”

It certainly can be overwhelming. The bad news is that being in Web design and development has gotten more complicated over time, and it’s not showing any signs of getting any simpler. The good news is that you don’t need to know every little thing in order to be a good Web worker, and many of the most important skills are timeless.

Are you good at understanding problems and figuring out solutions? Then you’ll be useful forever. Are you good at holding your customers’ hands, figuratively speaking, and making them feel comfortable through the creation of their website? Then you’ll be useful forever. Do you have good taste? Then you’ll be useful forever.

The rest you can figure out bit by bit, as you need it. I feel like my generic advice of “Just build websites� is relevant here. If you’ve read a bit about preprocessors and want to give them a try, then take a day and try it out on the next website you build. The same goes for anything you feel is newfangled or that you feel behind on. You don’t have to do it all at once.

For an overview of just some of the tools in my workflow, here’s a talk you can watch. The slides for that, as well as another one specifically about staying up to date on Web technology, are available here.

When To @extend

Ross Lavery asks:

“Could you provide some insight on when you prefer using Sass @extend (requiring a “semanticâ€� class of some sort to be added to the markup so that it can have @extend added to its style definition) versus simply adding a “non-semanticâ€� class to the markup numerous times. I’ve been struggling with which direction to go in, and Harry Roberts seems to prefer avoiding @extend for the most part, because it means coming up with a “semanticâ€� name for something that would have otherwise just required a class in the first place. I’ve had the same thought myself — having to just make up a silly name for a container for the sake of then extending a placeholder in Sass. Feels a bit backwards really.”

I wouldn’t pigeonhole @extend as being just a way to have semantic class names by extending non-semantic ones. Certainly it can be used that way, and, honestly, I have no big problem with that. I would think of it more generically, like: “Gosh I wish this class had the same stuff as this other class.� There are any number of reasons why that could be useful.

For instance, say you have this pattern on your website of a user avatar, user name and user location. It has some layout variations depending on how it is being used and on which page. You could have a class name like class="user-meta" for the most common variation, and then add classes to it (e.g. class="user-meta user-meta-small"), where the second class would override things set in the first class in order to get what you need. But that setting and overriding process is tedious and fragile compared to just setting what you want to begin with. Instead, you could have your .user-meta-small @extend a base class for all user-meta variations, and set what it needs on top of the base. The result is more efficient CSS (no setting and resetting) and more efficient HTML (one class instead of two).

Talking about this stuff so generically is difficult, though, and can lead to silly philosophical arguments. If you don’t like this, don’t do it. Naming is such a personal thing that as long as you have a system and aren’t often fighting yourself, you’re probably doing fine.

(al)


© Chris Coyier for Smashing Magazine, 2013.


Sneak Peek Into The Future: Selectors, Level 4


  

The buzzword “CSS4� came out of nowhere, just as we were getting used to the fact that CSS3 is here and will stick around for some time. Browser vendors are working hard to implement the latest features, and front-end developers are creating more and more tools to be able to work with the style sheets more effectively. But now, on hearing about CSS4, you might ask, “Hey, what about CSS3? Is it over already?�

We’ve been working hard to spread the goodness of CSS3, and now it’s obsolete? In fact, nothing’s wrong. It’s just natural evolution — a process that will help CSS as a whole — because “Level 3â€� and “Level 4â€� just follow the naming convention of the various documents of the specification.

Why Level 4? What About CSS3?

“Level 4� is just the number of the W3C document. Have you heard about the new “Filter Effects, Level 1� specification? Where should it go? To CSS3? CSS4? Hey, maybe CSS1 because it’s Level 1? Doesn’t matter, because CSS is just CSS. Selectors are the first document to reach the fourth level of the specification, and it’s still a draft, a work in progress. Each document is on its own when it comes to the specification number; the documents are developed independently of each other.

This is a big advantage, because finished parts of the document can be closed and set as recommendations — like Selectors Level 3. Finishing a document quickly and moving problematic parts to the next level helps to push the Web forward because it implements the specification one chunk at a time.

How the CSS4 logo could look like.

The buzzword “CSS3� will share the same fate as “HTML5�: we’re not talking about a specification number, but about the language as a whole. HTML5 is basically just the next version of the markup language, which adds support for new elements. But when you talk about it, you can bring up anything you want, from the audio API to Web sockets to geolocation (which isn’t even in the HTML5 specification).

The same goes for CSS3: it’s the shiny bit of magic that we do with CSS when building cutting-edge demos. You don’t have to know what part of the specification border-radius or box-shadow belongs to, as long as you know how to properly use it. Same goes for selectors; they’re just another version of the “Selectors� specification.

What Are Selectors?

The specification explains selectors as patterns that match against elements in a tree. Most of the selectors from the Level 4 specification are pseudo-classes. Selectors have been with us since the beginning of CSS, but now they are at the fourth level and have gotten a lot of cool new additions. Let’s jump into the action and see what’s interesting. I won’t describe the entire document — only the new additions in Level 4.

Logical Combinators: :matches, :not

Let’s start with logical pseudo-classes. The first, :matches, some of you might already know from Mozilla’s :-moz-any(), which was implemented a long time ago in Firefox 4. Thanks to this selector, we can group and match items in our CSS document. Why is it so useful? Well, the most basic use I can think of is to gather multiple definitions of anchor states into one. So, instead of this…

ul.menu li a:link,
ul.menu li a:hover,
ul.menu li a:visited,
ul.menu li a:focus {
   color: red;
}

… we can just do this:

ul.menu li a:matches(:link, :hover, :visited, :focus) {
   color: red;
}

Simple, right? Although this example might look silly, it shows the power of the :matches pseudo-class, and it can be used in more complicated situations:

article:matches(.active, .visible, p#important) {
   background: red;
}

The second logical combinator we’ll look at was introduced in the CSS3 specification, but it became even more powerful in Level 4. I’m talking about :not, the simple negation pseudo-class, which now can take a list of selectors as parameters:

p:not(.active, .visible) {
   color: red;
}

The code above will apply red to all paragraphs to which the active or visible class are not assigned in the markup.

Location Pseudo-Classes: :any-link, :local-link

Thanks to the location pseudo-classes, we will have more control over the styling of links. First, :any-link (a temporary name that could change) gathers definitions of a:link and a:visited into one, so you don’t have to write them both:

a:link,
a:visited {
   color: red;
}

Now, it won’t matter whether a link has been visited or not. It will be styled the same either way:

a:any-link {
   color: red;
}

Our second pseudo-class, :local-link, is way more interesting. You could, for example, give a different style to the links that target your home page, leaving all others untouched:

nav :local-link {
   text-decoration: none;
}

Thanks to this line of CSS, links pointing to the current page will not have the text-decoration style, so they’ll look different than the others in the menu or breadcrumb.

Let’s see another example:

:not(:local-link(0)) {
   color: red;
}

This style will apply red to all external links. (You could add, say, an icon or background image to them if you’d like.)

As you can see in this last example, :local-link can be used with a parameter. The number in the parentheses determines the level of the URL path that will be checked and matched against every given link. Sounds a little complicated, but an example should clarify:

nav :local-link(0) {
   color: red;
}
nav :local-link(1) {
   color: green;
}
nav :local-link(2) {
   color: blue;
}
nav :local-link(3) {
   color: yellow;
}
nav :local-link(4) {
   color: gray;
}

Suppose the current address is http://end3r.com/2012/10/20/some-title/, and you have these links in the breadcrumb:

  1. Home
    http://end3r.com/
  2. 2012
    http://end3r.com/2012/
  3. October 2012
    http://end3r.com/2012/10/
  4. 20 October 2012
    http://end3r.com/2012/10/20/
  5. Article
    http://end3r.com/2012/10/20/some-title/

The first link will be red, the second green, the third blue, then yellow, then gray.

Time-Dimensional Pseudo-Classes: :past, :current, :future

This pseudo-classes is very handy for users of screen readers. With only one line of CSS, the word being spoken can be given a different style (think karaoke-style):

p:current {
   background: yellow;
}

This will highlight the word being spoken in yellow.

The second use case is styling subtitles for the WebVTT video format, changing their color and other properties. The :past and :future pseudo-classes refer, respectively, to elements that have been selected and ones that will be selected.

UI State Pseudo-Class: :indeterminate

While the UI elements of online forms can be given many interesting pseudo-classes, such as :enabled, :disabled or :checked, one is quite new: :indeterminate. As you may know, checkboxes and radio buttons have two states, either checked or unchecked. Either state can be enabled using the :checked pseudo-class (and :not(:checked) for unchecked). But what if you want to style inputs that haven’t been used? They’re neither checked nor unchecked, so their state is indeterminate. Easy, right? We can give nice styles to these inputs that haven’t been used yet or for which a default state hasn’t been set:

input.checkbox:indeterminate {
   background: #ccc;
}

Similarly, a progress bar could be given an indeterminate state when its percentage of completion is unknown:

progress:indeterminate {
   background: #ccc;
}

In this situation, we can target the default state and style it to indicate to the user that the time left to load a resource can’t be determined.

Tree-Structural Pseudo-Classes: :nth-match, :nth-last-match

Tree-structural pseudo-classes are also new and interesting in the Selectors Level 4 specification. With the help of :nth-match, you can now achieve more than ever. Curious how it works? Well, if you take the :nth-child pseudo-class, which selects an item, and combine it with the power of :matches, you’ve got the answer.

Suppose you have a list of links, some of which have the class active, and you want to select only the even-numbered items from the active links. We could use :nth-child(even) to select all of the even-numbered children in the list, but that’s not what we want, because then we wouldn’t be accounting for the active class. Nor is :matches(.active) sufficient, because then we’d be targeting all elements with the class active. This is where :nth-match comes in:

li a:nth-match(even of .active) {
   color: red;
}

Thanks to this one line, we can finally select only the even-numbered items from among those that have the active class.

This is just a simple example. We can achieve a lot more using the complex syntax An+B, like so:

p:nth-match(2n+1 of .active, .visible, #important) {
   color: red;
}

This combination of selectors we want to match here is more complicated. The :nth-last-match works exactly the same as :nth-match but starts matching from the end of the DOM structure.

Grid-Structural Pseudo-Classes: :column, :nth-column, :nth-last-column

Let’s apply some pseudo-classes to tabular data. We all know that tables are bad for layouts but good for data that warrants it. An HTML table is row-oriented (<tr>), so columns are missing out. Creating a column-based table is possible, but then you’d be missing rows because you can’t have both at the same time, and row-based tables are more popular. Being able to use CSS to style the columns in a table that is row-based and created in the DOM would be useful when you want to, say, alternate background colors. Of course, we could use additional classes or markup; but with a little help from Selectors Level 4, we can do it with grid-structural pseudo-classes.

:column(.total) {
   background: red;
}

:nth-column(even) {
   background: blue;
}

This will set red as the background color of every cell in the .total column, and blue for every even-numbered column in the table.

Now we can select columns just like rows, and even get crazy with something like :nth-column(3n+2). Just remember that columns are styled based on their order in the DOM structure, not how they are displayed on the page. Of course, a table isn’t the only thing that benefits from grid-structural pseudo-classes: column-based layouts are on the way.

Parent Selector!

This is the long-awaited Swiss Army knife, the holy grail of CSS. It is the most discussed aspect of the Selectors Level 4 specification, and it gives you a lot more power with CSS. Thanks to the parent selector (also referred to as the subject of the selector), you can easily style elements other than the default last ones in a selectors list. This can be super-useful when styling generated menus, and you avoid having to add classes for styling purposes only.

Let’s see it in action with the most basic example. Suppose we have a menu, a simple list of links. We want to be able to style it, but the PHP on the server is generating the menu, so we can’t change it. The problem arises when we want to style the li element based on the active class added to the anchor; we can style a using a.active {}, but we can’t get to the li element. The easiest thing to do would be to add the active class to the list element, not to the link itself — like so: ul li.active a — so that we can style both the list and the anchor if needed. The problem is that the menu is generated by a script over which we don’t have control, so we end up with ul li a.active.

In the normal structure of a CSS document, we always refer to the last item in the selectors list. In ul li a.active, that would be the link with the active class; in article p span, it would be the span; and so on. Thanks to the parent selector, we can change the subject of the used selector. This gives us incredible power and flexibility when styling:

ul li! a.active {
   color: red;
}

Now we can style the li element according to whether the active class has been added to the link. When we add the parent selector, we are saying that we want to style the li element instead of a.active.

We can also manipulate the background color of the whole page just by adding a simple link somewhere in the document:

body! header a.styleSwitcher:hover {
   background: red;
}

This applies a red background to the body of the document whenever the user hovers over an anchor with the styleSwitcher class. To do this without the parent selector, you’d have to add custom classes in JavaScript. It’s not impossible, but the native one line in the CSS is definitely the best solution for this.

Note: The first draft of the specification document (dated 29 September 2011) targets the parent selector with a dollar sign before the given selector ($li). The latest draft (22 June 2012) uses new syntax in which the subject of the selector is indicated by an exclamation mark after the given selector (li!). Of course, this could change (it’s just a draft), so don’t forget about it. What matters is that the parent selector will be implemented sooner or later, and the exact syntax is just a matter of preference. It doesn’t matter to me what it looks like, as long as it works properly in the browser.

To see the parent selector in action, check out the cssParentSelector jQuery plugin.

Summary

As you can see, the new additions to the Selectors specification look very interesting. I can’t wait to use them in my projects. The only problem is that we will have to wait for them to be implemented in browsers — although you can test some in the browser with the help of a JavaScript library.

State of the Document

Level 4 of the Selectors document is not yet an official recommendation — just an evolving draft (as demonstrated by the parent selector, which has changed a couple of times and is still in flux). You can’t rely on the document because it will certainly change in future. But there’s an advantage to this: you can take part in the discussion and suggest ideas. Everyone with an interesting point of view can add something that will eventually be made part of the official specification.

Implementation and Browser Support

Some think it’s hard to implement something that’s still a work in progress. Yes, that’s partially true; browser vendors start to think about implementation only when the documentation has gone from messy to solid. But even though we can’t use the goodness of Selectors Level 4 today, we can use something like Sel, one of a few engines that have already implemented some of the features. Thanks to shims and polyfills, we can start experimenting with features that will be available in our favorite browsers in the coming months and even years.

Other Level 4 Specifications

There are already other Level 4 documents:

All of them are still in development, so we will have to wait a bit for the next official W3C Working Draft. Of course, you can get involved right away and influence the decisions that will be made.

Resources

The first and most interesting place to visit, of course, is the official W3C documentation for Selectors Level 4. Just remember that it’s still in development. You can also check out a couple of interesting articles in the wild, like the one by David Storey, a W3C Working Group member.

Shape the Future

Help with the document, suggest ideas, comment on other people’s ideas — now is the best time to be a part of the future. Who knows? Maybe in a few years from now, you’ll be in the Working Group and will be responsible for an awesome breakthrough CSS feature that will be used by millions of Web developers every day? It’s an incredible opportunity: to be at the bleeding edge of a standard or, better still, to take part in the creative process as one of the main contributors!

(al)


© Andrzej Mazur for Smashing Magazine, 2013.


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress