The ‘nav’ abstraction
22nd September, 2011 in Web Development
This post comes in a similar vein to Nicole Sullivan’s genius The media object saves hundreds of lines of code.
An abstraction is basically removing a pattern from a specific idea and making a more generic idea out of it. That is to say, rather than writing the same similar patterns over and over, create a single more generic representation of those patterns and reuse that instead.
Nicole does this with her media block by taking a series of similarly constructed but different components and sharing their common aspects in a more generic way. This is a really sensible and useful abstraction whereby she can make a pretty much infinite amount of pretty different blocks of content using only the same handful of lines of CSS each time. Genius!
Her media block abstraction is a pretty common one, and one I’ve used myself. Today I’m going to share another abstraction that may well be even more common and hopefully just as handy; the nav abstraction.
I’m sure you’ve had loads of projects where you’ve had a horizontal nav, and also maybe a breadcrumb trail and possibly a list of logos that go in a banner-style list…?
If this is the case then I also imagine you might have written something like:
#nav{
list-style:none;
margin-left:0;
}
#nav li{
display:inline;
}
#nav a{
...
[styles]
...
}
.breadcrumb{
list-style:none;
margin-left:0;
}
.breadcrumb li{
display:inline;
}
.breadcrumb a{
...
[styles]
...
}
.sponsors{
list-style:none;
margin-left:0;
}
.sponsors li{
display:inline;
}
.sponsors a{
...
[styles]
...
}
Here we can see that, although we’re building three different things, we’re reusing quite a few repeated patterns to create similar looking things. We need an abstraction.
The nav abstraction
Now, I’m not sure whether nav is actually the best word to use; these three examples are all types of navigational constructs, but that’s more coincidence than anything else. As such I encourage you to please offer up your alternative recommendations in the comments, please!
What we need to do now is take out the shared patterns and create a fourth class of .nav:
.nav{
list-style:none;
margin-left:0;
}
.nav li{
display:inline;
}
.nav a{
display:inline-block;
}
Here we define our abstraction. We take the repeated bits and make the most granular construct we can. This will throw any list into a very basic/crude horizontal series of links which we can then extend to adopt more specific styles, like so:
.nav{
list-style:none;
margin-left:0;
}
.nav li{
display:inline;
}
.nav a{
display:inline-block;
}
.site-nav{
width:100%;
background:#eee;
}
.site-nav a{
padding:5px 10px;
}
.breadcrumb li:before{
content:"» "
}
.breadcrumb li:first-child:before{
content:normal;
}
.sponsors{
text-align:center;
}
Using a base abstraction and then extending it we can create our breadcrumb with this HTML:
<ol class="nav breadcrumb">
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
<li><a href="/about/us/">About us</a></li>
</ol>
Writing abstractions gives smaller CSS, removes unnecessary repetitions and makes simple elements of your design much more reusable. Nice!
By Harry Roberts in Web Development. Tags: Abstraction, CSS, DRY, OOCSS | 8 Comments »
Ordered and numbered lists; the differences
17th September, 2011 in Web Development
This is a really small blog post about ordered lists and numbered lists and their subtle differences.
Have you ever wanted to say something like ‘There are three things to look out for:’ and then follow with a numbered list with the three things in?
I’m pretty sure we all have, and that we’d all normally use an <ol> to get the numbers, right? That’s how you get numbers next to list items after all…
Well the problem here is that the numbering defines an amount, not an order. The order is usually irrelevant in this scenario.
To make more sense I’ve drawn up a small fiddle of examples and the reasoning in each.
Here we can see that, although we want numbers, we don’t always want order.
The trick I’ve started employing is is to have a .numbered class which I can apply to a <ul> to make it mimic the appearance of an ordered list, without semantically carrying the ordered weight. This is how I do it:
ul,
ol{
margin-bottom:1.5em;
}
li ul,
li ol{
margin-bottom:0;
}
ul{
list-style:square outside;
}
ol,
.numbered{
list-style:decimal outside;
}
There. As simple as that. These are pretty much my default list styles now, and all I’m really doing is making an unordered list with a class of numbered look the same as an <ol>.
By Harry Roberts in Web Development. Tags: CSS, HTML, Semantics | 9 Comments »
Writing efficient CSS selectors
17th September, 2011 in Web Development
Efficient CSS is not a new topic, nor one that I really need to cover, but it’s something I’m really interested in and have been keeping an eye on more and more since working at Sky.
A lot of people forget, or simply don’t realise, that CSS can be both performant and non-performant. This can be easily forgiven however when you realise just how little you can, err, realise, non-performant CSS.
These rules only really apply to high performance websites where speed is a feature, and 1000s of DOM elements can appear on any given page. But best practice is best practice, and it doesn’t matter whether you’re building the next Facebook, or a site for the local decorator, it’s always good to know…
CSS selectors
CSS selectors will not be new to most of us, the more basic selectors are type (e.g. div), ID (e.g. #header) and class (e.g. .tweet) respectively.
More uncommon ones include basic pseudo-classes (e.g. :hover) and more complex CSS3 and ‘regex’ selectors, such as :first-child or [class^="grid-"].
Selectors have an inherent efficiency, and to quote Steve Souders, the order of more to less efficient CSS selectors goes thus:
- ID, e.g.
#header - Class, e.g.
.promo - Type, e.g.
div - Adjacent sibling, e.g.
h2 + p - Child, e.g.
li > ul - Descendant, e.g.
ul a - Universal, i.e.
* - Attribute, e.g.
[type="text"] - Pseudo-classes/-elements, e.g.
a:hover
Quoted from Even Faster Websites by Steve Souders
It is important to note that, although an ID is technically faster and more performant, it is barely so. Using Steve Souders’ CSS Test Creator we can see that an ID selector and a class selector show very little difference in reflow speed.
In Firefox 6 on a Windows machine I get an average reflow figure of 10.9 for a simple class selector. An ID selector gave a mean of 12.5, so this actually reflowed slower than a class.
The difference in speed between an ID and a class is almost totally irrelevant.
A test selecting on a type (<a>), rather than a class or ID, gave a much slower reflow.
A test on a heavily overqualified descendant selector gave a figure of around 440!
From this we can see that the difference between IDs/classes and types/descendants is fairly huge… The difference between themselves is slight.
N.B. These numbers can vary massively between machine and browser. I strongly encourage you to run/play with your own.
Combining selectors
You can have standalone selectors such as #nav, which will select any element with an ID of ‘nav’, or you can have combined selectors such as #nav a, which will match any anchors within any element with an ID of ‘nav’.
Now, we read these left-to-right. We see that we’re looking out for #nav and then any a elements inside there. Browsers read these differently; browsers read right-to-left.
For a quick graphical reason as to why browsers do this then it is the same reason most of you will save time solving this puzzle by starting at the smiley face (the target) first and working your way back:

It’s route 1, by the way.
For an in-depth reason as to why they do this see this discussion on Stack Overflow.
It’s more efficient for a browser to start at the right-most element (the one it knows it wants to style) and work its way back up the DOM tree than it is to start high up the DOM tree and take a journey down that might not even end up at the right-most selector—also known as the key selector.
This has a very significant impact on the performance of CSS selectors…
The key selector
The key selector, as discussed, is the right-most part of a larger CSS selector. This is what the browser looks for first.
Remember back up there we discussed which types of selector are the most performant? Well whichever one of those is the key selector will affect the selector’s performance; when writing efficient CSS it is this key selector that holds the, well, key, to performant matching.
A key selector like this:
#content .intro{}
Is probably quite performant as classes are an inherently performant selector. The browser will look for all instances of .intro (of which there aren’t likely to be many) and then go looking up the DOM tree to see if the matched key selector lives in an element with an ID of ‘content’.
However, the following selector is not very performant at all:
#content *{}
What this does is looks at every single element on the page (that’s every single one) and then looks to see if any of those live in the #content parent. This is a very un-performant selector as the key selector is a very expensive one.
Using this knowledge we can make better decisions as to our classing and selecting of elements.
Let’s say you have a massive page, it’s enormous and you’re a big, big site. On that page are hundreds or even thousands of <a>s. There is also a small section of social media links in a <ul> with an ID #social; let’s say there is Twitter, Facebook, Dribbble and Google+ link. We have four social media links on this page and hundreds of other anchors besides.
This selector therefore is unreasonably expensive and not very performant:
#social a{}
What will happen here is the browser will assess all the thousands of links on that page before settling on the four inside of the #social section. Our key selector matches far too many other elements that we aren’t interested in.
To remedy this we can add a more specific and explicit selector of .social-link to each of the <a>s in the social area. But this goes against what we know; we know not to put unnecessary classes on elements when we can use (c)leaner markup.
This is why I find performance so interesting; it’s a weird balance between web standards best practices and sheer speed.
Whereas we would normally have:
<ul id="social">
<li><a href="#" class="twitter">Twitter</a></li>
<li><a href="#" class="facebook">Facebook</a></li>
<li><a href="#" class="dribble">Dribbble</a></li>
<li><a href="#" class="gplus">Google+</a></li>
</ul>
with this CSS:
#social a{}
We’d now have:
<ul id="social">
<li><a href="#" class="social-link twitter">Twitter</a></li>
<li><a href="#" class="social-link facebook">Facebook</a></li>
<li><a href="#" class="social-link dribble">Dribbble</a></li>
<li><a href="#" class="social-link gplus">Google+</a></li>
</ul>
with this CSS:
#social .social-link{}
This new key selector will match far fewer elements and means that the browser can find them and style them faster and can move on to the next thing.
And, we can actually get this selector down further to .social-link{} by not overqualifying it; read on to the next section for that…
So, to recap, your key selector is the one which determines just how much work the browser will have to do, so this is the one to keep an eye on.
Overqualifying selectors
Okay so now we know what a key selector is, and that that is where most of the work comes from, we can look to optimise further. The best thing about having nice explicit key selectors is that you can often avoid overqualifying selectors. An overqualified selector might look like:
html body .wrapper #content a{}
There is just too much going on here, and at least three of these selectors are totally unnecessary. That could, at the very most, be this:
#content a{}
So what?
Well the first one means that the browser has to look for all a elements, then check that they’re in an element with an ID of ‘content’, then so on and so on right the way up to the html. This is causing the browser way too many checks that we really don’t need. Knowing this, we can get more realistic examples like this:
ul#nav li a{}
Down to just:
#nav a{}
We know that if the a is inside an li it has to be inside the #nav so we can instantly drop the li from selector. Then, as the nav has an ID we know that only one exists in the page, so the element it is applied to is wholly irrelevant; we can also drop the ul.
Overqualified selectors make the browser work harder than it needs to and uses up its time; make your selectors leaner and more performant by cutting the unnecessary bits out.
Is all this really necessary?
The short answer is; probably not.
The longer answer is; it depends on the site you’re building. If you’re working on your next portfolio then go for clean code over CSS selector performance, because you really aren’t likely to notice it.
If you’re building the next Amazon, where microseconds in page speeds do make a difference then maybe, but even then maybe not.
Browsers will only ever get better at CSS parsing speeds, even mobile ones. You are very unlikely to ever notice slow CSS selectors on a websites but…
But
It is still happening, browsers still are having to do all the work we’ve talked about, no matter how quick they get. Even if you don’t need or even want to implement any of this it is something that is definitely worth knowing. Bear in mind that selectors can be expensive and that you should avoid the more glaring ones where possible. That means if you find yourself writing something like:
div:nth-of-type(3) ul:last-child li:nth-of-type(odd) *{ font-weight:bold }
Then you’re probably doing it wrong.
Now, I’m still kind of new to the world of selector efficiency myself so if I’ve missed anything, or you have anything to add, please pop it in the comments!
More on CSS selector efficiency
I cannot recommend the website and books of Steve Souders enough. That’s pretty much all the further reading recommendation you’ll need. The guy knows his stuff!
By Harry Roberts in Web Development. Tags: CSS, CSS Selectors, Performance | 20 Comments »
Do designers need to code?
13th September, 2011 in Industry
I fear I may be poking the hornet’s nest with this one, but here goes. My personal opinion on that question…
Do designers need to code?
This has been the question of the moment of late. Though, speaking of late, I may have missed the main period of discussions around the subject. Regardless, here’s my take… Disclaimer.
Is a web designer really a web designer if they can’t code?
A lot of the arguments revolve around the (false) fact that ‘designers can’t understand what they’re designing if they can’t build it’. This argument suggests that a web designer who can’t code is a fake who’s just blagging their way if they don’t know/understand how to actually build the websites they design…
This is wrong. By this token I should understand MySQL and programming and Project Managers should understand design theory and programmers should be able to manage clients. There’s a reason we have different job titles; people do different jobs.
A designer who can build websites is a designer–developer, a designer who can’t write HTML/CSS is a designer.
Designers should work with developers
One reason, I think, that people believe that designers should be able to code is that they need to honour their designs, they need to be sure their designs are buildable by being the ones who have the responsibility of building them.
The problem is not that designs need to be buildable, it’s that developers should be permitted to send designs back and make compromises. Designers and developers need to collaborate, not be combined. Designers need to keep pushing the envelope, making tricky and outside-the-box visuals that push the work of the developer forward. The developer needs to be able to work back the other way, show the designer the boundaries that cannot be broken. Designers shouldn’t lead developers, developers shouldn’t lead designers, there should be a happy middle ground where teams work together, specialising in their respective areas but understanding and appreciating each others’.
A designer who codes badly is less use to a developer than a designer who can’t code at all. Developers need designers, not bug making machines.
But the client was shown a PSD that needs to be honoured…
I think this may well be one reason why people believe designers should code; the situation where the client has seen a PSD and thus expectations are set. A developer hasn’t seen the visuals and is all of a sudden expected to build something he’s had no input in. For the most part this may not be the case at all, but it definitely could be…
The remedy here might be to make sure designers only create things that they can build, achieving this by making sure designers can code.
This is fixing the wrong problem, the problem here is a lack of communication and a lack of collaboration, not a lack of skills. Designers and developers should work together from the outset, working in the browser to ensure that a) the team is working as, well, a team and b) that a client is never shown a PSD (showing a client a PSD in 2011 is just foolish).
The recurring theme is collaboration… Designers and developers need to coexist, not be one and the same.
HTML and CSS isn’t easy…
…but it is easy to do badly. I know loads of designers who can make the most stunning visuals but their code is not a strong point. Sure, they can write HTML and CSS, but it’s not where they specialise or excel, in much the same way a lot of developers have no design sense.
A designer who writes bad code is less use than a designer who can’t code at all. Once a designer writes poor code then either a) a decent dev has to come along and spend time bug fixing, or b) poor code becomes a tangled mess off spaghetti CSS and browser hacks.
Do not undervalue the importance of HTML and CSS, they are easy to do badly, but hard to do excellently. You need excellence in both design and development, so leave each role to its respective person.
These rules introduce restrictions
If a designer needs to code what he’s designed then he’ll design to what he can do, not to what can be done. This is a fundamental mistake to introduce.
A designer who isn’t restricted by a secondary skill set will produce things outside the box, push the envelope and keep innovating. A designer who is limited by their dev knowledge is hemmed in, scared of pushing the boundaries for fear of creating themselves work they cannot complete.
By forcing one thing you are restricting another, this is not a good thing to bring into your team. What you need to do is keep the contact and collaboration (there it is again) between design and build to ensure that everyone is achieving their full potential.
Real life examples
I know two people, personally, who both excel in their given fields. One is a fantastic designer who constantly produces unconventional but stunning websites, the other is an incredible front-end and JS developer (among other things). The designer can write code, but it’s not his focus, he doesn’t write production code because the developer does that.
They have a dynamic working relationship whereby they collaborate (and again) and consult with each other throughout the whole project. The designs look incredible and they’re built very well. This is more valuable than a constrained designer forced into producing buggy, poor code to build designs they’re not fully happy with.
What do they need to understand?
If a designer doesn’t understand code then this is fine; they don’t need to understand code, they need to understand their medium. Having an understanding of the web is not the same as being able to build it.
A good designer working with a good developer is a team that is good at making websites.
Don’t dilute someone’s skill set by trying to expand it, play to the strengths of your team. Designers who can code do exist, but they don’t have to. If you are a designer who can code (and thus a designer–developer) then that’s great, if you’re a designer who can’t code, but work well with developers that can, then great!
But there is no right or wrong answer
Designers can code, sure, but they didn’t ought to be required to. No one should be saying that a web designer isn’t so because he can’t code, that’s actually pretty rude…
If you have the budget to hire two people then get yourself a designer and a developer. Your designer doesn’t need to be able to code, they just need to work well in a team.
However, if your budget dictates you can only hire one person then hire someone who is a designer and developer. If you need to hire a designer–developer then make are they’re sufficiently good at both. If you can only hire one person then your designer does need to be able to code.
Designers do not have to be able to code, no one can make such a sweeping statement. It depends what you need, what you are comfortable with, and what works best for your team.
Massive disclaimer
When I say designers and developers I’m separating people into two camps; designers (people who just design (people that the industry seem to have a problem with)) and designer–developers (people who design and code (the people the industry expect)).
I’m not saying designers write bad code, because a designer who can and does write code is a designer–developer. Designers are, by definition, people who don’t write code.
So if you are a designer and you think I’m saying you can’t write code when you can then I’m classing you as a designer–developer. If you’re a designer who can’t code then that’s great. Please, no one take any offence, because none is intended.
In short
Designers shouldn’t have to be able to code to be called designers; designers should be able to collaborate and understand the rest of the team and vice versa.
If you need a designer–developer then yes, your designer does need to be able to code. If you can afford a designer and a developer then they don’t.
As David Kaneda so rightly put it:
“Just a thought: Devs don’t need to learn design, designers don’t need to learn programming — people need to learn how to collaborate.”
By Harry Roberts in Industry. Tags: Design, Development | 42 Comments »
When using IDs can be a pain in the class…
11th September, 2011 in Web Development
There have been a few articles flying about lately which tell you never to use IDs in CSS selectors. I always get a little concerned when articles like this command rather than advise, they often neglect to take into account context and necessity. I’m going to try and offer up one decent reason here as to why IDs might trip you up unnecessarily (and how you can avoid the pitfalls).
Since authoring this article I have decided that a blanket ban is sensible. Save yourself many potential headaches and never use IDs in your CSS files.
ID selectors are fine, valid and perfect for styling unique parts of pages. They’re HTML/CSS basics, you can use one ID per page and style the relevant element with #the-id-you-chose.
IDs, as well as being non-reusable, carry quite a high specificity, take the following:
<p id="intro" class="excerpt">Lorem</p>
#intro{ color:blue; }
.excerpt{ color:green }
p{ color:red; }
Even though we define #intro first—thus expecting it to be overwritten by subsequent matching selectors—it still takes precedence over any other rules. This is the IDs heightened specificity, and this is where you can come unstuck…
Reusability
One argument against using IDs is that they can’t be reused, but to my mind this is a weak argument. The whole point of using an ID is that it’s unique; if you want to reuse something you’d use a class. Developers know this, developers aren’t stupid so to tell them not to use an ID because it’s not reusable is, in my opinion, quite patronising.
Also, some things just can’t be reused. Some designs would be wholly impossible to have, say, two content areas in. You couldn’t reuse that even if you wanted to.
Wild card
That is wild card meaning a person or thing whose influence is unpredictable or whose qualities are uncertain
and not to be confused with the CSS wildcard selector (*{}).
One of the main and, in my opinion, most valid arguments against using IDs is that they can introduce specificity headaches where you want them least, and it can be a total nightmare fighting your way back out.
Using an ID in a selector instantly adds a specificity wild card (note, not wildcard), and you might not want this effect. It is, in a way, similar to !important; it is a trump card that will override nigh on all other types of selector. You probably don’t always want this.
The best way to illustrate this is with a specific example.
Let’s imagine you’re building a site and one of the requirements is to have a reusable Twitter widget that needs to be placable wherever the client chooses. Let’s for example say they want to kick things off with having the widget in the header and also in-page, at the bottom of an article. The Twitter widget’s styling must remain consistent.
So, let’s look at some example code.
Here we can see that we have a small specificity problem, the #header a rule has a lot higher specificity than .tweet a and therefore the links in the widget adopt the header’s (unreadable) colour. Remember that the Twitter widget’s styling must always remain the same so this is not ideal whatsoever.
We can work around this by adding a new selector to the .tweet a rule Or, even worse, we could add an !important to the relevant declaration. Shudder…
Now, you don’t need me to tell you that this is far from a nice solution, as soon as that widget gets put in the #footer we may well have to add yet another selector, which will prove a maintainability nightmare. This is not a very future-proof fix.
This is where using IDs can be a pain for you, where a specificity trump is introduced.
A better fix: add a class instead of (or as well as) the ID on that header div, thus: http://jsfiddle.net/csswizardry/gTZGq/3/
That now brings the specificity gap way down to, well, zero. Removing the ID means that you now don’t have to fight yourself out of a self-induced specificity war.
I did mention that you can add a class as well as the ID or remove the ID completely. It depends…
Remove IDs completely?
We’ve covered where IDs can trip us up and be but they serve a purpose other than style-hooks; they can be used as fragment identifiers for marking landmarks in the page.
I’m sure you’ve seen ‘Skip to navigation’ or ‘Jump to content’ links in pages, and these wouldn’t work without our IDs so we need to keep those in as well as adding our new class.
So, as is the case with most development conundrums, it’s all about context. You know your context better than I, or anyone else does, so don’t let anyone else tell you what to do. If you want to keep an ID for completeness or for fragment identifiers then do, it’s totally your call.
Final word
So yeah, IDs aren’t evil, they’re perfectly valid and a blanket ban on them is stupid. Use your own knowledge and context of the project to use the most suitable and sensible solution.
Don’t stop using IDs, just be aware of where they can cause you headaches and know where to sensibly circumvent them. Anyone telling you not to use them at all is not wrong, but they’re definitely not right…
By Harry Roberts in Web Development. Tags: CSS, CSS Selectors | 27 Comments »