Thursday, January 31, 2013

Design Centric And Layered CSS Files

One of the ideas I always find myself coming back to is separating different aspects of design into layers. Typography on one layer, color on another, grids on yet another. By constraining all, but one layer, the unconstrained layer can be more deeply explored.

One way I think about this is how to best organize css files to take advantage of this layered approach to design. My thinking is a design centric approach to stylesheet organization would allow for better experimentation and learning and possibly make maintenance easier.
I’ve struggled in the past trying to implement (and perhaps explain) this idea and I suspect what I’m looking for lies in some recent css thought that I’ve yet to look into fully.
  • Revising flawed practices
  • OOCSS and SMACSS
  • CSS preprocessors
My aim with this post is to serve as an introduction into the above, from the perspective of this design centric css concept. It’s also here to push me a little into looking deeper into each of the 3 topics and to jot down some general thoughts and ideas.
Layers of fabric

Layered Design

The basic idea is relatively simple. It’s that we can learn, work on, or maintain, one aspect of design independently of others. Imagine you’re working on an existing design and you’d like to overhaul the color scheme. You should be able to work on this without having to make changes to the typography or underlying grid the site is built on.
This can be a great way to learn design. With so many different things to learn and practice and it’s impossible to tackle them all at once. The same way we set constraints before beginning a project we can set constraints on our learning and limit the design palettes we work with in order to experiment with fewer things at once.
Of course, for a design to be most effective it needs a sense of unity and harmony across all these layers. Picture one set of parallel planes, each representing a design layer, and another set of parallel planes representing things like unity and concept that cut across the first set of planes connecting them.
  • Typography
  • Layout/grid
  • Color
  • Imagery
  • General aesthetics
  • Content
  • Interaction/experience layer
There’s no question that the above work best when they work in harmony with each other. Any grid you create would naturally be based on something like type or image sizes. The point is that we could study grids better by holding to a fixed set of typographic characteristics or holding colors to grayscale while we explore different font choices and type characteristics.
Texture woven into a circular layered pattern

A Design Centric and Layered Approach to CSS

I think most of us write css top down. We style the main header or masthead and work our way down the design through content areas and asides, until we reach the footer. We end up with our css organized around these large sections of our layout.
We probably also have sections for a base set of styles and another for common classes we use throughout our html, and perhaps a set of reset styles. The css for our main navigation bar is all in one place as is the css for your sidebar.
This approach is easy when developing as we code in the same order as we see elements in the design and it makes sense if your goal in maintenance is to rework your entire navigation to have all the navigation code located in one place.
There’s nothing wrong with the above, but I wonder is this how we can best maintain a site? Is it truly how we’d realign a design.
Isn’t it just as likely we’d want to change the entire color scheme of a site as we’d want to solely rework the navigation bar? Might we want to modify a site’s layout without altering the general aesthetics of buttons, and other design elements?
Lately I’ve found myself wanting to change something like the baseline grid for a design and with this top down approach the styles affecting the baseline are located throughout the entire file. It would be much easier if those styles were all located in one place or at least set up to be more easily changed.
For example take something like the following.
1
2
3
#primary {
  margin: 2em 12.5% 3em 0;
}
Right and left margins are more aligned with layout. Top and bottom margins are more connected to a baseline grid. Now consider the above rewritten as
1
2
3
4
5
6
7
8
9
10
11
12
/* -- placed in a layout section -- */
#primary {
  margin-left: 2em;
  margin-right: 0;
}

/* -- placed in a baseline subsection
      within a general typography section -- */
#primary {
  margin-top: 2em;
  margin-bottom:3em;
}
It’s certainly more code, but I wonder how much easier a set up like this would be when wanting to change only the baseline or only the layout.
Naturally whether or not this is easier to maintain depends on what you’re more likely to modify after the initial design is complete. Are you more likely to rework your footer without touching your header or are you more likely to change the color scheme affecting both while leaving the type intact. Of late I’ve begin to think it’s the latter more than the former.
There are a couple of problems I’ve encountered when trying to develop with this approach in mind.
  • It’s easier to develop initially with a top down approach.
  • It’s not always clear in advance what you’ll want to change, confusing how best to organize things.
  • Some styles seem appropriate in multiple sections.
With the first it could simply be a matter of being used to a certain way of developing. However, I get the feeling top down is generally easier to start with and that refactoring the code would become necessary to organize how I want. It’s an extra step though. With the latter two items it’s hard to know in advance what’s going to be better.
Reading glasses

Where to Look Next

While I’ve been thinking about all this some new thought about css in general has gained prominence.
The idea of revising some flawed practices comes from Nicole Sullivan who’s suggested some of the things we hold as absolutes in the way we code shouldn’t be seen so absolutely. They were developed years ago under a different landscape and it’s time to rethink them.
OOCSS and SMACSS come out of this rethinking and are ways to develop more around reusable classes and to organize our css around these reusable classes.
I think in the end what I’m looking for will be found mainly in css preprocessors like Sass and Less. If you’ve been playing along as you’ve read this post, the thought of being able to use variables has possibly come across your mind once or twice. However I suspect the first two will also contribute to what I’m after.
In any event I’d like to explore each of the above topics in the coming weeks. If you’ve already looked more deeply than I have into any of them please share your thoughts, especially in regards to how they might fit into my design centric and layered approach to css files.

What’s All The Fuss About Vendor Prefixes?

You’ve probably seen talk the last couple of weeks about browser makers moving to adopt the -webkit prefix in their non-WebKit browsers. Mozilla appears to be leading this move and the response from the developer community has been to strongly suggest this as a very bad thing.

Collage of browser logos

The Issue

In a nutshell vendor prefixes exist to allow browsers and developers experiment with css properties like transitions that aren’t quite standardized yet. Each browser uses their own prefix, -webkit, -moz, -o, -ms, etc. and when we want to implement one of these properties we should use all these prefixes along with the non-prefixed version.
Through the above, browsers and standards bodies can see how everything is working and ideally the information helps finalize the spec at which point browsers and developers move to support the non-prefixed version only.
If we as developers have been doing things right we already have that non-prefixed version in our code and nothing breaks.
However all is not perfect.
  • Some vendor prefixed properties are not part of the spec.
  • Some are proprietary and may never find their way into the standards.
  • Some web developers are using these proprietary properties.
  • Some browsers feel the need to support these proprietary properties or be seen as less capable.
  • Some specs are often painfully slow to become standards.
The danger is that we find ourselves back in a time where sites list warnings like this site works best in browser x. Please update your browser.

What Can We Do?

I won’t pretend to understand every nuance of what’s at stake here. As a developer my main concern is I want to be able to transform an element here or animate something there and I just want to know how to do that and which browsers it will work in.
With that information I can make an informed choice about whether or not to use something and just as importantly where in the stack from “has to work” to “cool feature for those few who’ll be able to see it,” it should be added.
As developers we should do a better job of using vendor prefixed properties. We shouldn’t rely on them to the point of our sites breaking without them. We should lean toward not using proprietary features, except at the top of the progressively enhanced stack. And we should be better about using all vendor prefixes instead of just one or two.
Those of us who write about things like multi-columns and flexbox should be clearer about what is part of the working spec and what’s proprietary and not evangelize the proprietary as ready for use.
Vendors could dial back a bit on the proprietary stuff and drop support for prefixes once they are no longer needed. The W3C for it’s part could speed up its own process moving specs to the recommended stage.
We could all do something to help the situation.
W3C logo

Additional Resources

Again I won’t pretend to understand every nuance in this issue and it’s possible I’ve mischaracterized a few things above. I’m still trying to sort some of this out, but think it’s important enough to want to present the issue sooner rather than later.
Here then are some of the articles I’ve collected these past couple of weeks. They aren’t in any specific order other than the order they found me. A search for vendor prefixes will lead to plenty more.
Have you thought about this? How are you currently using vendor prefixed css? Any ideas for a workable solution?

Is It Time To Change Our CSS Practices?

We’ve been using css as the presentation layer of web pages for quite some time. I’ve personally been using it for about 10 years and like many, much of my css practices were developed nearly as long ago. Is it time to change those practices?

Nicole Sullivan thinks so and I have to agree. She’s been giving presentations about our flawed css practices for at least the last year, and I think longer than that.
Last week I talked about how I’d like to organize css files around different aspects of design and mentioned a few css related topics I wanted to cover in the coming weeks. This is the first of those posts.

Our Flawed CSS Practices

Above are the slides for Nicole’s presentation on css flawed practices. I couldn’t get the video to embed here, but the previous link will take you to it. The video is 35 minutes long and worth a watch if you want the complete picture.
Though some of the specifics have varied from presentation to presentation, Nicole’s thoughts come down to a handful of different concepts. Below are practices the industry has held for years that perhaps need to change.
  • Sites need to look the same in all browsers
  • Pixel based sites are bad
  • You should never add non-semantic markup
  • You should use descendent selectors exclusively
  • Classitis is bad and to be avoided at all costs
I hope we all agree that as an industry we’ve accepted that sites are never going to look the same in all browsers no matter how hard we may try and we should take a more progressive enhancement approach to development.
I disagree with Nicole’s idea about using pixels, though. She’s seeing this entirely in terms of page zoom and considers the move to ‘em’s and other relative measurements as no longer necessary.
The ideas behind responsive design and designing from the content out are right to call for more relative based measurements for most things.
Let’s look at the last 3 items on the list in a little more detail.
Various css selectors

Descendent Selectors

We’ve been taught for years that best practice is to use descendent selectors to style our html. However this approach can become difficult to maintain and even lead to possible performance issues.
For example you might set styles on your generic h2. You then want the h2s in your sidebar to look a little different and further complicating matters you want a specific h2 in the sidebar to look different still
1
2
3
h2 {font-family: "Helvetica"; font-size: 1.2em; color: red; margin: 0}
#sidebar h2 {font-family: "Georgia"; font-size: 1em; color: #000; margin: 1em 0;}
#sidebar .related h2 {font-family: "Helvetica"; font-size: 0.9em; color: red; margin: 0}
The above isn’t overly complicated, but it’s not too hard to imagine it becoming more and more complicated as you create ever more specific selectors that need to be overwritten. Later a change needs to be made and you have to write even more specific selectors or worse add an !important declaration, because you can’t figure out how to make something specific enough to take hold.
I’m sure you’re written the occasional
1
#sidebar .related h2.boxed ul ul a {styles here;}
or something like it before. I know I have. I try my best to start with the least amount of selector specificity as possible when writing general styles, but that only postpones the problem. Our way of doing things sometimes leads us into specificity conflicts.
Person at the beach thinking the about word semantics

Semantic Markup

The basic idea behind semantic markup is to reinforce the meaning of the content being marked up. For example if you want to include a quote, you’d use blockquote tags. You could use an ordinary paragraph and style the paragraph to look like a blockquote, but that carries less meaning. Similarly you wouldn’t wrap an ordinary paragraph in blockquote tags and then style the blockquote to look like a paragraph.
Semantic markup and classes are generally a good thing because:
  • They’re cleaner and clearer to read
  • They’re easier to maintain
  • They’re more accessible to devices
  • They’re more search engine friendly
  • They communicate more information
Does this mean we can never stray from semantic code?
Consider grid frameworks with classes like grid_7 and container_12. They aren’t semantic because they don’t describe the content. Instead they describe the presentation of the content. Still they can be a great benefit to designers in developing, reading and maintaining the code.
While I do think semantics are good and important I also think it’s ok to add some non-semantic code We don’t need to be 100% semantic at all times. Better is to understand how and where semantic elements can help in order to decide when and where to use them. We should strive toward semantic use of html without being a slave to it.
Rusty picture frame around a demolished building

Classitis

One way to avoid the specificity problem that comes with using descendent selectors is to use more classes, especially if you’re not against using markup that describes presentation.
For example you might create a generic frame class to serve as a frame around some images on your site. Those images get class=”frame” added and those meant to be seen sans frame won’t have the class. Right away this reduces specificity issues as we don’t have to write and overwrite css styles on different parts of the page.
Later you may decide that some frames will be more sleek and modern and others will be more decorative. The styes common to both can remain in the basic frame class while the styles differentiating each get their own modern and decorative classes.
1
2
< img src="" alt="" class="frame modern" />
< img src="" alt="" class="frame decorative" />
1
2
3
.frame {styles common to both;}
.modern {styles for modern only;}
.decorative {styles for decorative only;}
In Nicole’s experience using classes in this fashion greatly reduces the amount of css we end up writing. This naturally plays out more the larger your site and css. On Facebook they were able to realize a 19% reduction in css (after gzip) and a 44% reduction in html (before gzip). You and I might not see the same results, but we’d likely see results.
There’s something very logical to using classes like this. We can create presentational objects that can easily be reused across a design. Again think of the grid systems or my frame example. At the same time there might be a downside in that we’re now coupling our html and css more.
Part of the idealized beauty of using css for presentation is the thought that with a few changes to a css file we can completely redesign everything on a site. If we’re adding all these extra classes does that cause problems? It would be hard to change a 12 column grid into a 16 column grid without changing the classes that were added through the html for example.
In practice though this idealized version of css doesn’t hold up. Some things we can easily change site wide by making a few css tweaks, including some layout changes. More often a complete redesign calls for structural changes to the html. Your 12 column grid doesn’t become a 16 column grid through css changes alone. It’s going to require html changes.
This doesn’t mean we should all go class crazy and use them for everything, but it does mean we don’t need to run away from using classes entirely. Somewhere in between there’s a good balance of using classes as presentational objects.
CSS written in blue on a black background

Summary

You may or may not agree with all or any of the above as flawed practices. Overall I tend to agree with what Nicole is suggesting and where her ideas lead, which is essentially to build sites with a reusable set of classes instead of sticking with descendent selectors.
I do have my reservations here and there. I don’t want to overdo the classes, but I do think a class-centric approach to html and css is generally a good one that allows for more design flexibility along with easier maintenance and a reduction in code.
I can see where it could lead to some difficulty if you’re looking to make wholesale changes as in a redesign, but more and more I think you’d encounter the same difficulty whether you’re using classes or descendent selectors and this probably isn’t a significant issue.
Mostly I think these ideas and questioning our practices makes a lot of sense, particularly now. The last year or two has seen so much new thinking in how we design and develop sites that now is the time to question much of what we hold as true and see if it still applies.
This rethinking leads us to some new concepts. As a reminder here are some topics I want to look at in the coming weeks.
  • abstracting css
  • oocss and smacss
  • css preprocessors
What do you think? Is Nicole right? Is it time to change some of our long held practices? Is there a danger in doing so?

Why Abstraction Can Improve Your CSS

How we might organize css files differently and whether or not some of our long held best practices aren’t as best as we thought. We might be able to improve things by reaching a little further into the development world and learning to make better use of abstraction in our design process.

Abstract photograph from a detailed closeup of a traffic sign and its shadow

What Is Abstraction?

“Abstraction is the ability to define a new concept in terms of other, more simple concepts,” in the words of Chris Eppstein, who’s post, Why Stylesheet Abstraction Matters, is one I’ll be leaning heavily on in writing this post.
Abstraction attempts to factor out implementation details so you can focus on fewer concepts at one time. I suspect most of you have used a php include statement at one time or another. It’s a simple example of abstraction. You want to include the same set of code in the header to each page on a site. No need to reinvent that code over and over. Write it once, place it in its own file, and include that file wherever you need it.
The principle of DRY (don’t repeat yourself) calls for abstraction.
Other common abstractions you might already use:
  • css classes
  • WordPress template_tags
  • php functions
  • grid frameworks like 960 and Blueprint
  • libraries like jQuery
Let’s look at the first. A css class is an abstraction. You define a set of styles that can be reused anywhere in your html. Someone working in the html alone doesn’t need to see all the details of the class. They just need to know that by adding class=”frame” to any html element, they get a consistent frame style applied.
Abstractions make the complex easier to work with. Take jQuery. Look at the explosion of Javascript solutions since its introduction. jQuery is a lot easier to learn and work with than Javascript itself. It’s easier because it hides low level details you don’t really need to know, like how to make an Ajax request. You just want to make the request and get a response. How it all happens is probably less important to you.
Scale of justice

Some Pros and Cons of Abstraction

Abstraction isn’t a perfect solution. It has a few downfalls, thought the pros generally outweigh the cons. Here are some of those pros and cons.
Pros:
  • Compatibility — The hidden implementation can be made to work across browsers, devices, etc.
  • Ease of maintenance — The code is maintained in one place
  • Productivity — It’s quicker to use the abstraction than reinvent it’s details
  • Reuse of code — Aids DRY principles
  • Refactoring — With implementation in one place it’s easier to improve the code
  • Organizational clarity — Less visible code is easier to read and follow
  • Reduces errors — With code is in one place errors aren’t repeated across a project
Cons:
  • Additional learning curve — The abstractions need to be learned
  • Loss of knowledge about what’s being abstracted — Learning the abstraction doesn’t necessarily mean understanding the underlying language
  • Finding code — Sometimes it’s not so easy to find where the implementation details are located
  • Fixing code — If you don’t understand the underlying language it could be difficult to correct low level errors
1962-D, Oil on canvas by Clyfford Still

How Can We Abstract CSS?

I’ve already mentioned a couple of ways, classes and frameworks. A class creates a reusable set of styles that can be applied anywhere in your html. The person applying the class doesn’t need to know the details of how the background-color is set.
1
2
3
4
5
.box {
  background-color: green;
  background-color: #0f0;
  background-color: rgb(0,255,0;
}
They just need to know it’s visually green. Instead of having to think about the implementation details they can work at a higher layer in the design.
Creating reusable classes is at the heart of both OOCSS and SMACSS. These classes can be chained to create even more flexibility and abstraction.
Frameworks might be collection of different classes you apply to create something more complex like a grid. They might also be a collection of styles applied directly to html elements to create something consistent and maintainable.
CSS is a relatively simple language to learn. Once you understand how to use selectors and properties and gain some additional understanding of how precedence works, you’ve got much of the language. That simplicity is sometimes limiting though and creates complexity for the designer/developer. It’s easy enough to understand that floating something to the left does indeed float it to the left. What’s harder to do is understand how to use floats to build a fluid 3 column layout.
The simplicity of css also leads us to repeatition. You’re either going to specify the same color over and over again or repeat the same series of selectors in multiple places, once to define a color, another to define a width and so on. Worse though is when you want to change a color used many times. Search and replace is about our only option other than manually finding every occurrence that needs changing.
Object oriented programming languages
Variables could easily fix the above. Wouldn’t it be better to define !link_color once at the top of your stylesheet and then apply color: !link_color; in the rest of the file. In terms of abstraction the variable becomes a new higher level concept that’s defined by something simple, a value. The abstraction is easier to work with.
Even with something as simple as variables, there are those who suggest they should not be added to css.
Their arguments don’t appear to have stopped others from pushing toward a css with variables.
Functions are familiar abstractions to anyone who works with a programming language. The implementation of the function is written once and then the function is called whenever we need that implementation. CSS already has some built in functions like rgba() and url(). What’s mainly absent is an ability to define new functions.
Expressions create new values by combining values, variables, operators, and functions. If you’re working with elastic grids you’re likely familiar with the expression:
result = target ÷ context
which helps us turn a fixed grid into a flexible one. CSS expressions could give us a way to define some things like this once in terms of variables and place the result into a new reusable variable. It’s a way to build up higher level variables from lower level variables.
Mixins are the contents of a selector (the properties and values) without the selector itself. They sit in for larger blocks of css and can be passed variables to control behavior. For example
1
2
3
4
5
6
7
=border-radius(!border-radius)
  :border-radius: !border-radius
  :-webkit-border-radius: !border-radius
  :-moz-border-radius: !border-radius
  &#58;-o-border-radius: !border-radius
  :-ms-border-radius: !border-radius
  :-khtml-border-radius: !border-radius
is a Sass mixin for using border-radius cross browser. Using the mixin whenever you want to add a border-radius to an element you would add
1
2
div 
  +border-radius(0.5em
Much simpler than having to write out all the vendor prefixes every time. Just as nice is that as browsers drop the prefix in favor of the standard you only need to make the change once, in the mixin.
One last abstraction I’ll mention is Macro Expansion, which generates selectors and styles through variables, loops, and conditionals. I’ll save the details for when I talk about Sass, but the general idea will be familiar if you’ve worked with any programming language.
Abstract painting of sunset on a beach at low tide

Summary

As currently exists css is a pretty simple language to learn and use. It’s simplicity is a benefit to helping more people learn to use the language, but that same simplicity can be limiting in what it enables you to do.
Abstraction is a way to use simple concepts as building blocks to create new and higher level concepts. They hide implementation details and allow you to focus on using the abstraction instead of having to rebuild it time and again. Abstractions offer a variety of benefits, though not without some cons thrown into the mix.
CSS already gives us one abstraction in the form of reusable classes and OOCSS and SMACSS take classes to a new level. Developers have built additional css abstractions in the form of frameworks that combine classes or groups of selectors to make site development quicker and easier.
Unfortunately some fundamental abstractions like variables and functions are missing. Fortunately these missing abstractions exist in css preprocessors like Sass and Less.
Have you started using OOCSS or SMACSS? How about Sass or Less? Any thoughts on how abstractions have helped you design and develop better sites?

How Should You Format Your CSS?

Does it matter how you format and organize your css? Are there compelling reasons to writing single line css as opposed to multi-line css? Or in the end is it all a matter of personal choice?

I thought it was a conversation worthy of a post and also fit with the recent talk here about different ways to write css.
Instructions for exam format

Why CSS Formatting is Important

If the only reader of our css was a browser, then how the code was formatted wouldn’t matter. We’d all minify our css and be done with it. You and I might not be able to read the minified code, but browsers would be fine with it. In fact we probably should be minifying our production code at this point.
However, we do need to read our css and likely have others read it as well. Given that human beings will be reading your css the basic goals of formatting should be.
  • Readability
  • Maintainability
While we should write code that we can both read and maintain first and foremost, we can’t ignore that other people will likely read our code at some point. We should also think of our future selves. I’m sure you’ve written css that seemed clear when you wrote, but not so much several months later when you needed to modify it. I know I have.
CSS with multi-line formatting

Different Styles of CSS Formatting

There are a variety of ways to format css, each with some pros and cons. Ultimately I don’t think there’s a single way css needs to be formatted as we all have different preferences. Still we should be aware of the pros and cons of the choices we make.
One of the first formatting choices you’ll make is to write single line or multi-line css.
Single line css — makes it easier to find selectors across a document, however it’s usually harder to find a specific property within a selector. This wasn’t so much an issue in the past when we didn’t use too many properties, but as css has given us more to play with and vendor prefixes have entered the picture, our list of properties has grown.
1
2
3
4
5
#globalnav { }
#globalnav a { }
#globalnav a:hover { }
#globalnav li ul { }
#globalnav li ul a { }
Having all your selectors grouped together like above, each on a single line makes it easy to scan a file and find blocks of code that style a particular design element, in this case a global navigation bar. It would be quick to zero in on #globalnav a for example, even in a large document.
However once you start adding in some properties it’s not so clean and nice.
1
#globalnav {list-style: none; font-family: 'Helvetica'; border-radius: 7px; background: #777; overflow: hidden; -webkit-box-shadow: 2px 2px 10px #ccc; box-shadow: 2px 2px 10px #ccc; -moz-box-shadow: 2px 2px 10px #ccc; -o-box-shadow: 2px 2px 10px #ccc; padding: 0; background-image: -webkit-linear-gradient(#777, #555); background-image: -moz-linear-gradient(#777, #555); background-image: -o-linear-gradient(#777, #555); }
That’s one long line of css. Not too hard to find the #globalnav selector, but not too easy to find specific properties within.
Multiple line css — is the opposite. It’s easier to find properties within a selector, since each get’s it’s own line, however it’s usually harder to find a specific selector as more scrolling up and down is needed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#globalnav {
  list-style: none;
  font-family: 'Helvetica';
  border-radius: 7px;
  background: #777;
  overflow: hidden;
  box-shadow: 2px 2px 10px #ccc;
  -webkit-box-shadow: 2px 2px 10px #ccc;
  -moz-box-shadow: 2px 2px 10px #ccc;
  -o-box-shadow: 2px 2px 10px #ccc;
  padding: 0;
  background-image: -webkit-linear-gradient(#777, #555);
  background-image: -moz-linear-gradient(#777, #555);
  background-image: -o-linear-gradient(#777, #555);
}
Much easier to read the properties of #globalnav when written on multiple lines, isn’t it? Of course the other selectors around it have probably been pushed off the screen and so finding #globalnav a might not be as quick and easy.
Drawing of a school of fish organized into a single larger fish

Organizing and Improving CSS Formatting

You probably have a strong preference for one of the two styles of formatting above. In either case there are things you can do to improve readability and maintainability.
Ordering css properties — With either single or multiple lines we can be consistent with the order we write properties. Jonathon Snook suggested an order of:
  • box properties
  • border properties
  • background properties
  • text properties
  • other properties
Seems like a good idea even if you prefer a different order of property groups. In the multi-line case we could leave a blank line between groups and in the single line case we might compromise and start each group on a new line.
Tabs between properties — With single line css some people have attempted to use whitespace through tabs to improve readability.
Unfortunately properties don’t necessarily line up in columns well since they aren’t the same from one selector to the next. I’ve tried this a few times and outside of special cases have never found it to work well.
Indentation of nested selectors — WIth multi-line css some will use indentation to show selector relationships and structure. The selectors aren’t technically nested, but use whitespace to make them appear that way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#globalnav {
  property: value;
  property: value;
}

  #globalnav a {
    property: value;  
    property: value;  
  }

    #globalnav a:hover {
      property: value;  
      property: value;  
    }
While showing the relationships is appealing, I haven’t had much luck with this style of formatting either as I find the “nested” selectors get lost and appear to be properties of the main selector at first glance. It might just be case of needing to get used to it, though.

Higher Level Improvements

There are some things we can do at a higher level to improve css readability and maintainability regardless of your choices with anything above.
Sectioning and organizing files — At the very least we should be organizing our css files in some way. All your global navigation styles in one section and your footer styles in another. Perhaps you’d prefer all typographic styles in one location and all color styles in another.
It’s not always clear how best to organize sections though, which is what led me into this recent look at css.
Taking things a little further you might choose to use a single css file or multiple css files. Multiple files might be cleaner, but require additional http requests.
Comments — You certainly want to use comments for for major sections and probably for specific properties to remind yourself why you chose a particular value. If you still use the occasional hack for one browser or another a comment is likely necessary.
Comments need to strike a balance. Commenting everything is just as bad as commenting nothing,
Better naming of classes and ids — This is always a good idea. Good names need little explanation, though it’s not always obvious how to best name classes and ids.
Abstract art with the word Formatting

My CSS Formatting Practice

You might be curious about my formatting practices. I’m ashamed to admit they haven’t changed much over the years. I still format based on habits established long ago.
Early on I made the decision to write single line css for a couple of reasons.
  • Less whitespace to keep file sizes smaller. This is in the days before minification.
  • Ease of finding selectors. I used less properties in the past
Since then I’ve experimented here and there with refining things, but nothing has stuck. When presenting examples here I do write multi-line css, since I agree it’s much easier to read for short blocks of css.
I’d like to tell you I’ve been good at commenting my code, but I can only say I’ve been good on an inconsistent level. I generally keep files organized, but the comments don’t always find their way in. I’m happy to say I’m getting better at being more consistent.
I’ve typically organized css styles in a top down approach to mimic how the html is structured, as I suspect most of you do. There are sections for base styles and common classes, but otherwise my css is typically organized as follows:
1
2
3
4
5
6
7
8
9
10
11
#header { }
blocks of styles relating to the header

#main-content { }
blocks of styles relating to the main content

#sidebar { }
blocks of styles relating to the sidebar

#footer { }
blocks of styles relating to the footer
I’m been consistent in regards to naming classes and ids, though I’ve changed my convention over the years.
CSS

Closing Thoughts

I think how you format your css is mostly a matter of personal choice. If you’re working in a team it makes sense to agree upon a consistent system, but when working for yourself it’s hard to argue against writing it your own way. You aren’t going to know the preferences of those who later read your code so why try to predict it.
Your main choice will be single or multiple lines. After that you should try to refine your approach to make things more readable and maintainable. You can organize files and properties, try tabbed or nested indentation, or anything else you think will make your css clearer.
I have a feeling my current preference is going to change once I explore css preprocessors. I think it’ll be enough of a difference to shake me out of long ingrained habits. I assume at that point I’ll write multi-line and nested preprocessed css and output minified css for production.
However, viewing source code was and is a great way to learn to code and I want to provide that resource here. Whether that means not minifying or whether it means providing a non-minified version for download is something I’ll decide when I get there.
How about you. Do you have a formatting preference? Do you write single line or multi-line css? What additional refinements do you make to improve readability and maintenance?

Sunday, January 27, 2013

Some Practical Guidelines For Writing CSS

Do you follow a consistent set of practices when writing your css or do you write a few lines of css that work before move on to the next line? Did your best practices grow organically or did you follow a set of guidelines for writing your code?

For a number of weeks, I’ve been looking at my own css practices and considering a variety of new ideas for formatting and combining css and html. A few weeks back in an article about css formatting I received a couple of comments pointing me to additional resources and ideas.
 I want to look at article that offers guidelines for writing css.
Occupy DC guidelines written on a piece of cardboard

Some General CSS Guidelines

These css guidelines come from the folks at CSS Wizardry. I don’t want to repeat the entirety of their article here. Instead I’ll offer a few highlights and encourage you to check them out in full on Github.

They advise beginning each file with a table of contents that’s mapped to the different sections of the file. I’ve always wondered how useful these are since you still need to scroll the file to see anything, but I suppose a quick overview at the top can be helpful.
1
2
3
4
5
6
7
8
9
10
/* ------------------------------- *\
             Contents 
\* ---- -------------------------- */
/*
Reset
Base
Layout
Modules
Navigation
*/
They also suggest using a prefix for each section so they begin each section with a comment in the form of $[section name] in order to make searching quicker. Since only the section heads will have the prefix a search will take you right to the section, which is an interesting idea as the file can’t link directly to its parts.
1
2
3
/* ------------------------------- *\
             $Layout
\* ---- -------------------------- */
Bitmapped text spelling 'syntax error'

Syntax and Formatting

When it comes to syntax and formatting a number of ideas are presented.
  • Always use multi-line, which helps with version control.
  • Properties should ordered by relevance and not by the alphabet.
  • Use dashes instead of underscores or camelCase
  • Always include the trailing semi-colon
  • Comment as much and as often as possible, including commented markup to give context to a block of css
  • Indent your css to match how your html is nested. With vendor prefixes align along the colon:
I’m hesitant to want to comment everything as I think it can go too far and make it more difficult to scan a css file, however most of us don’t comment enough and the idea to add commented markup is interesting.
Another interesting guideline was to avoid using the shorthand property. The idea is that a shorthand essentially overwrites default values on what’s not included and you often want to keep these defaults. For example if you only want the margin-top to be 0 then say that instead of margin: 0, which also sets the left, right, and bottom values.
Ultimately you want to make sure the shorthand is really what you want before using it. In my own coding I typically start by writing the individual property, but once a couple of individual properties are present I’ll convert them to the shorthand.
2-column layout with header and footer and 3 modules in the sidebar on right

Components and Layout

They suggest writing your markup before your css when building new components. This allows you to visually see where css properties can be inherited and to stay in an OOCSS or DRY frame of mind when creating components. Ideally you’d identify visual patterns and build base objects for them. Then extend these objects with classes.
I can’t say I write all my html before getting to the css. I have a tendency to write the general layout markup getting containers for footers, content, asides, footers, etc, set and then writing the css to generate the basic layout. Then I go back and start filling in the containers and styling each before moving on to what’s inside the next container.
For layout you should keep components and modules free of widths and heights. Let your modules get their size from the underlying grid system layout. This allows components to remain fluid. For measurements use % for layout (widths) and rems for font size. Keep line heights unitless. I’m not 100% sure if rems are prime time ready yet, but if they are then yes this is the way to go.
This makes a lot of sense. Relative measurements are best for flexible layouts and I like the idea of setting these measurements on the basic layout as opposed to individual components, which we often want to be 100% of their containers anyway. By not setting widths and heights on everything we allow our design to better reshape itself under different conditions.
Jukebox selector

Selectors

A few guidelines about selectors, which should be familiar to you by now if you’ve been reading some of my recent posts.
  • Keep selectors efficient and portable
  • Avoid location based selectors as they lead to tighter coupling in html and css
  • Longer selectors likely have performance issues. Keep your selectors shorter
Avoid overqualified selectors as a class name usually enough. You generally don’t need to include the element in front.
1
.classname { }
is better than
1
div.classname { }
It’s usually better to place a class on the element you want styled instead of on containing elements and then drilling down to the element you want to style.
1
2
3
4
5
6
7
<nav>
  <ul>
    <li><a href=""></a></li>
    <li><a href=""></a></li>
    <li><a href=""></a></li>
  </ul>
</nav>
If you want to style the links above add the class to the links as opposed to adding one to the nav element and then digging down to the links. The former will keep your selector shorter and help it be more efficient and more portable.
Speaking of class names, they’re neither semantic nor unsemantic, something we’ve seen before. Class names are sensible or insensible.
Stay away from IDs for css. Add them to your html for Javascript (behavioral) hooks only and use classes for the styling hooks. It’s ok, however, to use !important when you absolutely know the rule should take precedence.
Lightbulb laying on a notebook of ideas

Additional Ideas

A few other ideas I found interesting
  • Avoid magic numbers and absolute values since they rarely work beyond the one special case
  • Avoid conditional stylesheets for IE
  • When debugging remove code before adding more
I’m not sure I follow the logic for the conditional comments guideline. Until more people are on IE9 and beyond I think our best bet for getting things to work on some older versions is to use conditional comments.
I know they’ve always had some controversy around them, but they’ve also seemed the most workable solution to me. You generally don’t need to use a lot of conditional comments or have them point to a lot of IE specific code, but they often help. Having said that I can’t say I’ve needed to use them as much in the last couple of years.
In regards to debugging, when something isn’t working as you expect, the problem is likely in the code already written and not in the code yet to be written. It makes sense to first remove what’s causing the problem and then rebuild your css instead of just adding more css on top of the problem. The latter will only lead to specificity nightmares.
Some nested css for navigation from the CSS Wizardry guidelines example

Summary

While I don’t necessarily agree with each and every one of these guidelines, I think they’re mostly right on track and make for good practice.
By following them, the developers at CSS Wizardry suggest the need for css preprocessors will be reduced, though it’s certainly ok to use preprocessor as extensions of above. They shouldn’t be used as an alternative, however. I don’t think these guidelines would eliminate the need for preprocessors, but I can see how they can help.
What do you think of these guidelines? Agree with them? Disagree? What additional guidelines do you use when writing css?

The Definitive Guide to About Me Pages

One of the most important and least used aspects of any website is the “About Me” page. It’s not enough to have an interesting site and great product if your visitor can’t find a way to relate to you. Never under-estimate the power of personality. The internet isn’t a cold, sterile environment. As a matter of fact, within the last 15 years, it’s developed into a community addicted to interactivity, and communication. If you don’t believe me, check out Twitter. Twitter is a good example of why “About Me” pages are crucial. If you can amass a group of followers based on 140 characters of random biographical chatter, it’s a safe bet that those readers would also like to know a bit more about you.
In this guide, we’ll walk through the most essential aspects of any “About Me” page. At the end, you’ll be totally empowered to make your own page, because we’ll strip away all of your excuses!

1. Answer These Questions:

Who am I?
What can I do for you, the visitor?
How can I be contacted?
About Me PagesAn “About Me” page can be whittled down to these three questions. Visitors want to know briefly who you are, why you decided to make a website, and how they can reach you if they want to hear more.
Who am I? A lot of successful “About Me” pages start off with “Hi, my name is…” Having a personal introduction is a great way to start off. Your “About Me” should come across as if you were talking face to face with your visitor. Although I personally prefer a first person narrative (“I am, We are…”), for corporate or more professional websites, it may be better to go with the third person voice (“Jimbo Designs is…”).
Don’t overwhelm the reader with too much information. Of course they want to know more about you, but it’s safe to leave out details like the name of your high school gym teacher, or the color of your first car. Your “About Me” page should expand on the purpose of your website. If your website is about the wonderful world of Photoshop, your “About Me” page should include how you got started on Photoshop, and briefly skim through your accomplishments.
What can I do for you, the visitor? Put yourself in the visitor’s shoes. The reason they’re clicking your “About Me” page is to relate to you. They want compare notes to see if you and they share the same awesome traits. Let’s face it, if a visitor’s searching for your “About Me” page, that means that you have piqued their curiosity and in some way inspired them to care about who you are. Don’t let them down!
Sometimes visitors will click on your “About Me” page because they want to know about how you can help them. You should always answer this question. To do this, first consider your visitor pool. If potential clients, explain your services. If fellow enthusiasts, share how you first fell in love with your subject matter. If learners, tell them why you’re qualified to make such a website.
About Me PagesHow can I be contacted? Some websites have separate “Contact” pages, which is recommended, but you should also include your contact details on your “About Me” page to save the visitor from clicking too many pages. A good idea is to add social media buttons on your “About Me” page. Everyone loves Twitter, and in addition to that, include your Facebook, LinkedIn, Delicious, and Flickr pages. Be careful, though, if you’re including a Facebook identity. We all know how carefree a Facebook identity can be, but if you’re promoting a professional brand, your Facebook profile picture shouldn’t be a questionable image from Spring Break.
In certain websites, it’s a good idea to have a separate “About Me” for you as an individual and one for your website. This especially pertains to websites that aim to help people or sell services.

2. The Photo

About Me PagesAfter you’ve tackled the words, it’s time to choose an image that encapsulates your personality. A photograph on your “About Me” page is not optional. It gives the visitor another way to relate to you. And, if you don’t include a photograph of yourself, your “About Me” page will seem incomplete.
There are several ways you can go with this. Observe:
The “Reliable Professional” Photo
About Me Pages
The “Awkward Child” Photo
About Me Pages
The “I Looked Good in that Photo” Photo
About Me Pages
The “I’m So Funny” Photo
About Me Pages
The “Me with My Hobby” Photo
About Me Pages
As you can see in all these examples, an “About Me” photo can range depending on your personality and intended audience. Although tone doesn’t always translate well in words, it’s easy to recognize in pictures. When a visitor sees your image, they can start piecing together a more accurate idea of you.
Another note about the photo is that it should be a photo of your face, not an photo of your right foot, or a random stock image. Privacy is definitely an issue on the internet, but through the process of creating a website, you open yourself up to some sort of transparency. Why not further the bond between you and the visitor by showing them who you are?

3. Highlight Great Posts

The “About Me” page is the perfect place to do some cross-promotion. Often times, after arriving at your home page, a first time visitor’s next click will be to your “About Me” page. Give them a general scope of your website, such as “Must See” or “Most Popular” posts. That’s a sure-fire way to drive more traffic to the posts you’re most proud of. It’s also a comprehensive way to welcome visitors to your site.

4. Create an Indented Listing for you “About Me” Page on Google

About Me Pages
This step isn’t as well known as others, but guaranteed to drive more traffic to your site. An indented listing is when a second page from your website is listed directly under your main website on Google’s search page.
The effect is that visitors are more likely to click on your website.
The “About Me” page is the perfect way to create an indented listing under your website. In order to do this, you’ll need to ensure that your website is within the first ten results on Google for a particular keyword. That keyword may be the name of your website, or brand.
Start off by optimizing your “About Me” page with the same keyword from your home page (or whichever page ranks in the top ten results). Next, link your “About Me” to that page. Now, go to the main page (that’s in the top ten results), and create an anchor text that links to your “About Me.” Of course, it also helps if you get inbound links from other sites. So, be sure to leave comments below, and link to your “About Me” page in the website box!

Change the collation on a MySQL database via PhpMyAdmin

Change the collation on a MySQL database via PhpMyAdmin

MySQL supports different types of collation and characters sets. The following article will walk you through how to change the collation for one table or the entire database. 




Change collation for the entire database
  1. Connect to the database using phpMyAdmin
  2. Select your database and click on Operations from the top menu 
  3. On the drop down menu under collation select the character or collation that you intend to use for the database. 
  4. Click on Go and the change is effected for the entire database
Change the collation for one table
  1. Connect to the database using phpMyAdmin
  2. Select your database
  3. Select your table and click on operations from the top menu.
  4. Under the Table options menu select the collation/character for the table
  5. Click on Go to make the change for the table

Saturday, January 26, 2013

Tips for Coding a Solid Frontend Interface in HTML5/CSS3

Website interfaces often require a large starting point to get going. You’ll need to spend some time planning out a design style or simple prototype in advance. But how do you go about starting the HTML5/CSS3 development cycle?
Featured Image - custom HTML and CSS code editor
In this article I would like to share a few tips and tricks for coding a spectacular frontend. Web development has never been easier to learn, but there are also a lot of ideas to follow along with. Experienced developers know what to look for and how to construct their pages for easy readability. These models are great to use not just for your own personal projects, but also on collaborations and with open source code releases.

Make your Documents Simple

This is my golden rule which I cannot pass onto enough developers. There is a tendency to overuse HTML elements and implement a lot of different classes within your markup. However I feel that any amount of space saved will improve the final result.
For example, most of my core div IDs are composed of the fewest letters possible. I’ll use #w for my wrapper div since it’s a quick reference and easy to identify. I would suggest carrying this method further into your CSS classes, because those are often used repeatedly in a webpage.
CSS document properties and stylesheet design
As another example I will often use .c for my container classes. These are often set to a maximum width and contain internal elements within a layout. Utilize this naming scheme to the point where you can still quickly recognize the conventions without becoming overly confusing. Obviously the class .tag is still shorter and easier than .linktag or .linkTag.
Data markup should also be fairly straightforward and easy to scroll through. Use HTML elements where they are appropriate – list items for lists, code/pre tags for source code, and tables for displaying tabular data.

Perform Browser Checks

This rule should be relative to your layout but still pertains onto all web developers. When you’re coding a website layout it’s commonplace to initially test your changes in a single browser. This is just easier since you don’t want to open 3 or 4 browsers after every little change.
Reddit.com on Mac OS X Opera Web Browser
But it’s important that you do take the time for browser-specific updates and bug fixes. You would be surprised how many valid HTML5 layouts will still break when ported over into Safari, Opera, or IE9. A good strategy is to build your layout to fit perfectly into whatever you normally use for a web browser. Then after you feel the job is complete enough go back and run some tests in all the other various rendering engines.
My default list includes Google Chrome, Mozilla Firefox, Internet Explorer 7-9, Opera, and Safari. If you are building a responsive layout it’s not a bad idea to check on mobile browsers, too. Both iOS and any Android smartphones will have different screen resolutions. These come into play if your responsive media queries aren’t implemented correctly.

Frontend Code Validation

This isn’t a requirement in the coding process but it’s nice to get into the habit of validating your webpages. The newest models do not cater to every meta tag and older XHTML specifications, so it’s common to find errors in your validation. But keep in mind this doesn’t mean your website is improperly coded. And it definitely doesn’t mean you must go back and “fix” your code.
Mozilla Firefox web browser validator html/css
For some clients these validation services may be mandatory. Not everybody will care about these labels since they are exactly that – just a label. But for those interested here is a nice HTML5 validator put out by the W3C(World Wide Web Consortium).
The W3C is full of people who debate the rules for new specs such as HTML5 and CSS3, so their website is certainly an authority on development techniques. They also have a CSS Validator if you want to give that a shot, too. There are many properties which will return an error such as -webkit-text-size-adjust. This is completely valid for mobile webkit browsers, and although it’s just an example you should try to ignore these egregious blacklistings of vendor-specific prefixes.

Learning from Past Mistakes

I think we all make mistakes at times because we’re only human. But mistakes come with the responsibility of admitting you were wrong and changing your techniques in the future. Not everybody will do this last step, and so they’ll continue making the same mistakes repeatedly.
It can be rough to accept there are parts of a website layout that you’ve completely overlooked. It can be helpful to have a couple web developers who you trust look over any skeptical source code. There are times when you’re staring at a project for hours and just cannot find the problem. It has happened to me a number of times and the quickest solution is often through a third party.
If you are not familiar with Stack Overflow then I definitely recommend setting up an account. You can register with an e-mail/password or through another service like Twitter or Google. OAuth is a very secure method since it’s one-click login without memorizing another password. The community is extremely helpful and very intelligent on a number of languages.
Flying above San Francisco, California houses
But my final point is to never get discouraged and never give up! Other developers are usually very friendly and happy to offer support where possible. Just be sure you can learn from other devs and take their lessons to heart. In a big world there will always be people with more knowledge on these topics. Advancing your education is all about what you do with this knowledge and how you apply any new found skills into your future projects.

Final Thoughts

Web development encompasses such a wide spectrum of languages and server knowledge. You really do need to spend a long time studying techniques and practicing your ideas before you will feel completely comfortable. But what a better time to advance your knowledge than right now?
I hope this article can offer just a few ideas to get you focused on bare-bones frontend development. HTML5/CSS3/JS are all individual languages within themselves. But as you go through the process to learn each one you’ll understand how they fit into the grandiose schematic for brilliant websites. Along with my suggested links feel free to share your own ideas with us in the post discussion area below.

How To Develop Scalable And Maintainable CSS

I wanted to discuss each a little and more importantly point you to both in case you haven’t seen them. Some of you have also provided even more for me to take in on the subject and I promise I’ll get to those links as soon as I can.
Andy’s presentation, CSS For Grownups: Maturing Best Practices, (found via Jeremy Keith) builds on the work of Nicole Sullivan with OOCSS and Jonathan Snook with SMACSS.
His talk mainly looks at moving from current descendent selector practice toward a more modular class based approach.
Nicolas’ article, About HTML semantics and front-end architecture, is more focused on html semantics and dispels the notion that all these class names are unsemantic. If you’re struggling a little to move toward classes due to worries about making your html less semantic I think his post will convince you that you don’t need to be worried.
The word Think spelled out in boards attached to a gate, with the K about to fall down

Why Rethink CSS Best Practices?

It’s relatively simple to learn the syntax and basic use of css. What’s not so simple is to create scalable and maintainable css systems. Many of the best practices we’ve developed over the years aren’t helping. If anything they’re leading us to develop less scalable and maintainable stylesheets.
This gets masked at times if you only work on smaller sites. With fewer instances of difficult to maintain code, you can usually overcome the maintenance problems with a little extra effort, but the issues are still there.
Even if you don’t currently work on large sites or plan to, you should still rethink best practices and improve your systems. Small sites grow larger. Personal goals change. New technologies and techniques spring up all the time and we should be prepared.
The main ideas behind all this rethinking of best practices is
  • To create us more maintainable css
  • To help our css coding practices scale
Let’s consider a couple of ways toward these goals, decoupling our html and css, and better choice of class names.
Slide showing selector as .social li:nth-child(1)

Decoupling HTML and CSS

Andy’s talk was in part about how we can uncouple css from html so our styles are less dependent on our structure. Less coupling leads to a more maintainable site.
At first glance it seems like adding classes to html increases coupling due to the added markup, but the opposite is actually true. Coupling is increased the more dependent we are on a specific html structure. Jonathan Snook referred to this as the depth of applicability. The greater this depth, the greater our html and css are coupled.
Unfortunately our best practices the last few years have been increasing coupling even as we thought we were decreasing it.
Compare the images from Andy’s slides above this section and just below. In both the css is simple. It’s adding a background image to each of three different social buttons. In the slide above the selectors take the form .social li:nth-child(x).
When this nth-child selector is used, structure and style are highly coupled. Changing the order of the html so the Facebook button comes before the Twitter button requires a similar change in the css.
On the other hand the slide below shows similar css, except the nth-child selector has been replaced by a class in the form .social .twitter. This requires that extra code (the new class) be added to the html, but now you can rearrange the order of the buttons in the html without having to make any changes to the css. There’s less dependence on the specific html structure.
Slide showing selector as .social .twitter
Later in the presentation Andy talks about different layers of css. He offers 4 in his example without suggesting these are the only 4.
  • Document
  • Base
  • Module
  • Layout
The concept should be familiar if you’ve looked through the SMACSS documentation. Andy’s idea is that a block of css should only affect one of these layers. He shows a variety of css styles and which layers they affect. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.promo-box {
  color:red;
  background: black;
} /*  module only */

.promo-box h3 {
  font-size:1.2em;
  text-transform: uppercase
} /* module and document collide */

.promo-box h3,
.promo-box h4 {
  font-size:1.2em;
  text-transform: uppercase
} /* continuing to add more document collisions */

.promo-box .promo-box-h {
  font-size:1.2em;
  text-transform: uppercase
} /* module only with the second class expanding on the first */
The two blocks in the middle tie things to the html structure by including the hx tags. You can imagine how this can quickly get out of hand as you add more headings or other elements. The combination of the first and last blocks of css above are best. Each affects only one layer of the css, in this case the module layer, and it makes the resulting css much more manageable.
Andy continues with an example of headings alone. I’ll let you check the presentation and slides for the details, but the gist is he transforms the typical hx styling we do to a class based approach.
1
2
3
h1 { font-size: 3.0em; } /* initial hx selector */
.h1 { font-size: 3.0em; } /* changed to a class named after the hx tag */
.h-headline { font-size: 3.0em; } /* changed to a class name that better describes it's purpose in the design */
He walks through lists in a similar fashion moving the css from ul.product-list li to .product-list li to .product-item.
Imaginary board game Semantopoly: The semantic and open web themed game that will get you sued by Hasbro

Semantics and Class Names

One of the best practices the industry is trying to change is to avoid classitis at all costs. We’ve been taught that classes are unsemantic and we should add as few as we have to. This isn’t true.
Nicolas’ article focuses on class semantics. He says there are different types of semantics. We tend to think content driven semantics when talk about the subject, but there are also agreed upon global semantics such as microdata.
He makes 4 points about semantics.
  • Content-layer semantics are served by html elements and attributes
  • Class names impart little semantic information outside of agreed upon standards
  • The primary purpose of a class name is a hook for css or javascript
  • Class names should communicate useful information to developers
He tells us that class names (other than the agreed upon) offer no semantic information to machines by default, however when chosen well they do communicate useful information to developers and so have semantic value. Because of this class names are always semantic since they always carry some meaning with them.
1
2
3
4
<div class="news">
  <h2>News</h2>
  news content
</div>
The above class name is a bad choice because it adds no additional meaning we couldn’t get from the content itself. It also ties the class name to the content and so can’t change easily. For example it wouldn’t make sense to present recent comments inside of a div with a class name of news.
Once again coupling has been increased, reducing scale and maintainability.
Our goal should be to develop reusable components that can contain a range of content types. The most reusable components are those with class names independent of the content they hold. Nicolas talks further about how we can make css components more reusable and combinable.
  • Javascript specific class names — (js- prefix) can help reduce the risk that changes break Javascript
  • Single-class css pattern — styles get defined on multiple classes so only one class is needs to be added to the html
  • Multi-class css pattern — styles kept more modular and multiple classes are applied to the html (preferred approach)
  • Structured class names — naming patterns to make presentational relationships more understandable
I’m only pointing out a few highlights here and skipping much of the detail. If you’ve been hesitant to use more classes thinking they’ll make your html less semantic, I think the article will convince you otherwise as well as offering some good advice for how to go about naming your classes.
It’s definitely worth a read.
A rusty lock securing a rusty green gate

Summary

Most of us have been following the same set of best practices for years. I certainly have. Unfortunately many of those practices were based on incorrect assumptions about coupling and semantics.
We’ve been making our html, css, and even javascript less maintainable for years. We’re used to it and have found ways to work around the problem or we work mainly on sites small enough to hide some of the issues, but those issues are there nonetheless.