September 1, 2014

Explaining the “Details” and “Summary” Elements

Lots of JavaScript libraries are developed to give us additional interactive widgets on websites. Equally, HTML5 has also interpreted a number of popular interactive components, making them into native web features. In this post, we are going to look into one such element called <details> (and in doing so the  <summary> element) which gives us an interactive widget similar to an accordion.

Using <details> and <summary>

The <details> element can be used anywhere within the scope of the <body>. To give a simple example, we may add it this way:

<details>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas, impedit.</p>
</details>

The above example shows the <details> element containing a paragraph, highlighting its similarity to other HTML sectioning elements. It defines a semantic section which in turn may contain child elements, such as images together with the <figure> element, form elements like <input> and <textarea>, and even nesting other arrays of <details>.

The only significant different would be in how browsers display this element on the front-end. Supporting browsers like Chrome, Safari, and the latest version of Opera will display it with a little triangle and a Detail line at the side.

The <details> element works like an accordion widget in that the content within it will initially be hidden. Toggling the arrow, or clicking anywhere which horizontally aligns with the arrow, will reveal the hidden content. We are also able to highlight it using the Tab key and either the Space or the Enter key to toggle it.

Note: AccesibleCulture covered accessibility thoroughly in Screen Readers and details/summary.

The Open State

Having opened the details element, if you now look through at the source with dev tools you will find that the browser has appended the open attribute while it is in this state. We can actually add the open attribute into the<detail> manually to display the content open by default.

<details open>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas, impedit.</p>
</details>

The Summary Element

The <details> element ships along with an element called <summary>; these two are meant to be used in conjunction but using the <summary> element is totally optional.

So what happens when you do use it? 

<details open>
    <summary>Hello World</summary>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas, impedit.</p>
</details>

Given the above example, the default Detail will be replaced with the Hello World.

Nesting

As mentioned, the <details> element may contain other nested <details> elements, like so:

<details>
    <summary>Hello World</summary>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas, impedit.</p>
    <details>
        <summary>Hi, How are you?</summary>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas, impedit.</p>
    </details>
</details>

This does present one visual issue (which wouldn't be the case with, say, nested lists) the browser default styling. As you can see below, the nested element is aligned to the left along with the parent which obfuscates the true hierarchy:

This is nonetheless easily addressed by adding some simple styles. So, let's see how we style these elements.

Styling Details With CSS

The <details> and <summary> elements can be styled just like any other block elements; select them through the element selector, a class, or an id and stack a pile of properties to style it.

details {
    padding: 15px;
    background-color: #f6f7f8;
    margin-bottom: 20px;
}

Additionally, you can use the attribute selector to specify styles for the open state.

details[open] {
    /* the style goes here */
}

The <summary> element can also be styled. Speaking of which, if you hover over a clickable element such as a button or an anchor, the cursor will normally turn into a pointer. But that's not the case for the <summary> element which is also clickable. The cursor will instead turn into the text cursor, which feels slightly unnatural, hence you might want to revise the default style, defining the cursor as pointer like so.

summary {
    cursor: pointer;
}

Styling the Triangle

And now for the question you've been dying to ask: can you style the little triangle? There's no standard yet, but Webkit has uses a pseudo-element for this purpose,  ::-webkit-details-marker. Through this we are able to customize the default arrow styles such as the color, the background color, as well as the arrow size.

summary::-webkit-details-marker {
    color: #fff;
    background-color: #000;
}

Unfortunately, replacing the arrow directly through the ::-webkit-details-marker is not possible — at least, at the time of writing. The only viable course is to replace it by using the ::before or ::after.

summary::-webkit-details-marker {
    display: none;
}
summary:before {
    content: "14"; /* the new icon */
    color: #696f7c;
    margin-right: 5px;
}

Browser Support

Browser support for these two elements has been well improved in the last two years. Back in the 2011 and 2012, Chrome was the only browser capable of rendering <details> and<summary> — albeit the implementation suffered from some accessibility issues. Safari and Opera has only recently joined the club.

So, as far as supporting Firefox and Internet Explorer are concerned, there are a couple of polyfill options to mimic the functionality, such as one developed by Mathias Bynens, jQuery Details. Although this polyfill seemingly relies on jQuery, the file size is much smaller than the jQuery UI library counterpart.

Once implemented, style it just like always.

summary:before {
    content: "B8"; /* unicode character of the litle triangle  */
    color: #000;
    margin-right: 5px;
}

Further information about browser support can be found on caniuse.com.

Use Cases and Examples

You will likely have already have seen these elements in the wild. Whilst shopping online, for example, you may find some websites pack their products' lengthy descriptions in an accordion. Or else they might use it in the sidebar to filter results, like Payless, for example.

The <details> and <summary> element are also perfectly suitable for organizing FAQ items and feature list items typically found in a pricing table layout. I've created a demo which you can see here which you're free to abuse.

Conclusion

As Aaron Lumsden said in this post 

"websites are becoming more data driven and app-like"

so this new element is very much appreciated. Someday, perhaps with the advent of web components, building a website or a webapp will be less dependent on JavaScript libraries when adding a simple widget like an Accordion.

So, have you ever used <details> and <summary> in your website?

August 28, 2014

Introducing Avocode — PSD to Code Without Photoshop

Photoshop has been a part of web design for years, and it’s very likely to continue as such for a long time. If you design for the web using Photoshop, or you’re a developer who handles coding up PSDs, it’s likely there are a few issues you run into on a regular basis.

Even if you've transitioned from Photoshop over to Sketch for the design stage of your workflow, you'll still face the issue of coders needing access to software they otherwise wouldn't use. With either of the two programs, it's likely you'll hit speed bumps that are just par for the course when using tools whose primary purpose is design, not generating code for the web.

Made by Source

The guys at Source have been producing extensions for Photoshop since 2012. Their plugins are designed to ease some of the most common issues in the design to code process, such as creating CSS that accurately represents a design, and exporting images efficiently. 

I’ve been a long time fan of their CSSHat plugin, which generates CSS or preprocessor code from Photoshop layers. I also use their PNGHat plugin almost every time I use Photoshop, for exporting images to PNG, JPEG or Base64. You can see both of these plugins in action in my two part tutorial:

These plugins are focused on the developer stage of the site creation process; turning PSDs into fully functional websites. Given many developers don’t even need Photoshop for any other purpose than accessing PSDs, it’s a natural next step to see this type of workflow enhancement taken right out of Photoshop all together. 

That's what Source’s new desktop and web based tool, Avocode, is all about.

Avocode is a program which is purpose built for the process of going from PSD (or Sketch) to code. It doesn’t automatically generate sites for you, rather it gives you a set of tools which enable you to create sites in the way you personally prefer, but more efficiently than when working directly inside Photoshop or Sketch. Avocode aims to bridge the gap between the design and coding stages of web development.

Comin’ up

In this article we’ll look at how you can use Avocode to:

  • Open up PSDs for coding without Photoshop, and without emailing or uploading files.
  • Select layers, groups and move around in a design.
  • Generate CSS or preprocessor code for elements in your design.
  • Get accurate dimension measurements with which to build your layout.
  • Copy out text content for easy placement in code.
  • Extract color palettes and hexcodes from PSDs.
  • Export images, even from multiple layers, without having to deal with the slicing process.

Open PSDs Without Photoshop

With Avocode, PSDs are shared between designers and developers via an automated syncing process. If you’re a designer you’ll install a Photoshop plugin and, when your design is ready, you'll just hit a “Sync now” button to make your PSD available to the developer.

Additional ways to sync are on the way, with Dropbox as a confirmed option coming in a future release. Judging by the current beta 0.5.0 interface we might also see syncing via Layervault, direct upload and pulling files straight in from local storage.

If you’re a developer you’ll receive a notification through Avocode that a new design is available, at which point you can just open it up directly via a single click in the PSD browsing panel. This does away with the need for emailing mega-attachments or otherwise manually transferring PSD files.

Along with each design comes an in-built version management system. Progressive iterations of a PSD can easily be synced between designer and developer, again by hitting the Photoshop plugin Sync now button, with each version accessible through the PSD browsing panel. Avocode remembers the previous export settings of the images in the design, meaning tasks such as exporting newly updated images can be automated.

Selecting and Navigating

Once you have a PSD open in Avocode you’ll find interacting with it to be quite intuitive. Like Photoshop, Avocode has a Layers Panel where you can see all the PSD’s layers and groups. These layers and groups can all be shown or hidden, and you can also click to select any of them.

 

As well as selecting elements of the design via the Layers Panel, you can choose the Select Tool from the tools panel on the left, then click any item on the stage directly. To select multiple items, just hold down SHIFT and continue clicking the items you wish to select. 

Multi select works whether clicking directly on the stage or in the Layers Panel.

To pan around the design choose the Hand Tool then click and drag to move.

Generate CSS and Preprocessor Code

With any layer selected and the Inspection Panel open you’ll see the CSS for that item output in the panel's Code subsection, in either raw or preprocessor form depending on your preference. This uses the same CSS generation logic as the CSSHat plugin, which is still the most visually accurate CSS generator I’ve seen among the currently available options.

Grabbing the CSS for the item is as easy as clicking the Copy CSS or Copy LESS button, so you can paste into your stylesheet or directly highlight the lines you want to use and copy them from there. If you’re having preprocessor code generated, it will automatically include mixins from your preferred mixin library. The presently available options are:

  • LESS + LESSHat
  • Sass + Compass
  • SCSS + Compass
  • Sass + Bourbon
  • SCSS + Bourbon
  • Stylus + Nib

Get Accurate Layout Measurements

I’m sure I’m not alone when I say that finding the layout dimensions inside Photoshop can be a bit arduous. Avocode’s approach to this problem is very straight forward. To get the height and width of an item:

1. Choose the Select Tool and select any item, or multiple items.

2. Read the values at the bottom left corner of the blue selection highlight box.

3. Or, read the values to the right of the preview thumb at the top of the Inspection Panel.

To find the horizontal and vertical distance in pixels between any two items:

1. Choose the Measure Tool and select any item.

2. Hover over any other item and read the values next to the horizontal and vertical red lines.

Copy Out Text Content

If you have a text layer selected you’ll see a clipped preview of the content in the Inspection Panel, as well as its width and height, and a quick Copy text button you can use to grab the text therein for pasting into your code.

Generate a Color Palette

1. Choose the Color Picker Tool and move your mouse around the stage, watching the color preview until you have the color you want.

2. Click in that location and your color will be added to the Colors subsection in the Inspection Panel, with the hexcodes displayed for each.

Export Images

1. Choose the Select Tool and select any item, or multiple items.

2. In the Inspection Panel under the panel’s Export subsection click the little file icon with the blue plus sign on it to set your selection as an asset.

3. The name of your asset will be drawn from the layer name. Choose PNG, JPEG or SVG export, then click “Export now”. If it's the first asset export of the project you'll be able to choose a destination folder, otherwise the file will be exported straight away.

After you have set your selection as an asset it will also appear in the assets panel. From here you can click the magnifying glass icon to be taken to the folder storing your asset exports.

You can also click the "Get Code" button at the top of the panel, or the <> icon to the right of your asset's name, to generate HTML, CSS or LESS you can use to place the asset in code.

In the PNGHat plugin for Photoshop there is also control over the exact JPEG and PNG export settings as well as scaling options, so I imagine we’ll see these same controls ported over to Avocode soon.

To get an idea of what to anticipate in Avocode’s image exporting processes read more about PNGHat here: How to Export Photoshop Assets For the Web With PNGHat

Extra Features In Development

Right now Avocode is in private beta so there are still several very interesting looking features due to come out in the near future. The app is scheduled to move into public beta at some point this summer, after which we’ll see the official launch.

As the development moves along, here are some of the things we can anticipate:

Full Multi-Platform and Web Based Support

Whatever OS you work with, or even if you’re on a mobile device, you’ll be able to use Avocode. At the moment the closed beta version of Avocode is being put through its paces on Mac, but the full release of the native app will also run on Windows and Linux, and the web version will run in any modern browser.

Use With Sketch Based Designs

Source report they already have a working prototype to deliver all the same functionality for Sketch based designs. So if you’re a designer using Sketch on Mac, a designer using Photoshop on Windows, a developer writing code on Linux, or if you're using any other combination you’ll be equally ready to go.

Atom Code Editor Inside Avocode

Avocode is actually built on top of the Atom Code Editor produced by GitHub. What's really exciting about this is it means there will be a fully fledged, robust and feature rich code editor available right inside Avocode upon its public release. Being able to handle the entire coding process right inside a single app really caps off what is already shaping up as a powerful feature set.

Color Variables

As well as being able to grab the hexcodes for the colors added to your palette, you’ll also be able to assign variable names to each color for use in your preprocessor code.

In Built FTP and CDN Upload

As with many of the other functions on the way for Avocode, the ability to upload directly to CDN is already present in one of Source’s plugins, PNGHat, so we can guess that the functionality will be much the same. Images can be exported locally through Avocode, or alternatively you’ll be able to push them directly to a CDN and have the file location added to your CSS output. You’ll also have the option to FTP the images directly to your server on export.

Connect With TypeKit and Google Fonts

The introductory videos for Avocode mention there will be an option to integrate with TypeKit and Google Fonts when generating your font settings code. This isn’t yet in the closed beta or any of Source’s plugins so I’m not sure exactly how this will work, but I’m personally hoping it will streamline the process of putting together the appropriate URLs and code with which to call in various fonts.

Base64 and Sprite Sheet Export

The first stage of image export in the current closed beta version of Avocode is for JPEG, PNG and SVG. However Source already has a process established for Base64 generation through their PNGHat plugin for Photoshop, so I expect we’ll see them drawing from that code base to bring it into Avocode. They also intend to support production of sprite sheets along with the required CSS.

Export Code for iOS

The focus of Avocode will be the web until it has reached full maturity, however there are also plans in the works to enable it to be used as part of iOS development.

Source already have a plugin called iOSHat that works within Photoshop to generate Objective-C or Swift code from Photoshop layers for use in iOS development. It’s likely the support for iOS code export within Avocode will work in much the same way.

Packages for Custom Extensions

There is an intriguing menu item in Avocode; one which hints at the future extensibility of the platform, with some initial packages already in place:

Source say they were inspired by the release of Atom to adopt a similar method of allowing custom “Packages” to be created and shared among the community. We can look forward to seeing this pathway open up as development moves along.

Preorder to Lock In a 70% Discount

At the moment Source are steadily rolling out features and working in beta user feedback as they go along. When the software is publicly released it will be available via a subscription model for $240 per year.

However, if you get in early on the preorder you'll lock in a spot with a 70% perpetual discount, bringing it down to $69 per year instead. You'll also get access to the private beta, and during this period you'll be able to use the software free of charge. Your actual subscription only begins when Avocode goes to public launch.

Preorder spots are limited, and as of this moment there are fewer than 230 places available. To preorder: http://avocode.com/preorder.html

Useful Links

For extra information visit:

Conclusion

I'll leave the drawing of conclusions entirely up to you! What do you think, are you surprised by any of the features Source have announced? Will Avocode form a part of your future workflow? Let us know in the comments!

August 27, 2014

Working Harmoniously With Your Team on Web (and Email) Projects

In recent weeks, our team had the rather demanding task of designing ten email templates in time for the launch of Canvas, a new and easy-to-use email newsletter builder in Campaign Monitor

On top of the regular requirements which come with building templates for an email marketing service that designers use (for example, that campaigns look good, even on mobile devices!) there were a couple of extra things we needed to address. First and foremost, there was working collaboratively with design, testing and of course, amongst email coders to make this project happen. As it turns out, developing a process around that was indeed, a project in its own right.

Working in and across teams is a) hard, and b) really demands both tools and processes to be in place upfront. If you struggle with getting the results you want from your design projects - even if they aren't email related - then you'll likely relate to these points. With any luck, you'll find our experiences useful when overcoming your own challenges with team collaboration.

Chasing Waterfalls

As an email coder who, for many years, has taken a brief > code > delivery approach to tasks, using a similar waterfall approach seemed natural when developing each of the Canvas templates. To give you an idea of the complexity of the task, each of the ten templates consists of multiple layouts and a selection of elements (text fields, buttons etc), with every piece requiring close collaboration between both our email code and design teams. As was the case when I started years ago, collaboration can be fraught with danger, even amongst the most well-behaved of us.

So, here's a look at the seven steps, from kickoff to testing and handover, that our team worked through to create the templates. Again, while these reflections are on an email project, you'll likely find these workflow tips just as applicable to the web.

1. Choose the Best Tools for Communicating

It was really important that we found a means to collaborate and share between design, email coding and whoever wanted to jump into the project. 

We tried a number of approaches to discussing and clarifying issues, including the use of Shipment (for design reviews), LayerVault (for version control) and a HipChat room (for team chat). At the end of the day, we selected Basecamp, a popular team collaboration app. Not only was it already in use and familiar to many within Campaign Monitor, but it's pretty good for organizing coding tasks and facilitating deeper discussions in teams.

We use Basecamp to collaborate internally and between teams

For template issues (for example, rendering glitches), JIRA, an issue and project tracking app, was selected - again, a tool that is very familiar to the team. Using JIRA allowed us to also loop in our cohorts in the testing team, without forcing them to use tools outside of their existing workflow.

2. Get to Know the Design

Once everyone was settled on collaboration tools, it was time to receive the Photoshop mocks in PSD format from the design team. This was a bit of a discovery phase (and perhaps not so waterfall-y after all) requiring email developers like myself to have a good look through PSDs of both the desktop and mobile versions of a template.

A desktop mock for the Mason template
A desktop mock for the Mason template

Things that we focused on included identifying standard layouts that email coders are generally familiar with (eg. 1-3 static columns), vs non-standard, more adventurous ones. Seeing how the same layout or element looks translated between desktop and mobile is always very interesting; thankfully our designers are pretty used to working with responsive emails (and their quirks), so aren't prone to making outrageous demands as far as layouts go!

3.  Identify Tricky Layouts and Elements

Anyone who has coded a web or email design from scratch knows that often, finding out what works and what doesn't across multiple platforms can be quite an exploratory process. With our templates, some of the elements had to be coded and tested aside from the template-in-progress, to ensure they could be incorporated into the design. As always, some things may not look exactly the same across all email clients (or browsers, as is with the web), but they should at least degrade gracefully - and look good.

Also, if something in a mock turned out to be actually impossible to achieve, it was good to give that feedback early, since design changes can often have ripple effects.

4. Create Assets

Once fairly confident that the template mocks provided by our designers could be turned into a rock-solid email template, it was time to slice away and create assets. This includes both graphic elements in the template itself, and placeholder photos from the mockup.

To ensure images are optimized for Retina displays, we exported them from the PSDs provided at 2x size, and then resized down to 1x using the image's width and height attributes. Yes, this is something that email designers do, too!

One of the icons zoomed in for detailed work
One of the icons, zoomed in for detailed work

The exception to this were background images (for example, those used in bulletproof buttons), which were usually exported at both 1x and 2x sizes.

5. Yes, Let’s Code This Thing!

While each Canvas template is designed to be fairly dynamic as far as combining layouts and elements goes, we found that coding a long, static HTML file with placeholder content helped us envision the final product. We developed a framework from scratch based on LESS, with each template's styles.less file containing a number of variables for basic styles and calculations, followed by styles which are specific to the template. CodeKit was used to process the LESS files and speed up browser testing.

As an aside, the ever-helpful Stig on our team created a Chrome extension for overlaying the PSD designs over HTML pages. Called Blueprint, this extension allowed the team to achieve an unprecedented degree of pixel-perfection.

While a lot of folks may rail against making things look "the same" across all email clients - or browsers for that matter - there is certainly virtue in aspiring for that goal, to achieve a level of quality and perhaps even appease a fussy client to some degree!

6. Test IRL, Not Just Virtually

As far as testing both the "desktop" and "mobile" versions of an email design goes, our process was not that different to what happens on the web. Sadly but truly, we'd do a lot of squishing and stretching the browser.

However, at least as far as testing goes, simply viewing the template in Chrome (or your browser of choice) is never enough. At this stage, we'd usually import the campaign into Campaign Monitor to run a quick Design and Spam test (being an email project) and/or tested in Litmus (which also provides automated browser screenshots). If the design looked off in virtual tests, we'd progress to live device tests. 

In addition to using a few virtual machines in VMware, we also turned to our "device lab" - largely consisting of mobile handsets - in order to test as thoroughly as possible. If you don't have the benefit of a device lab in your workplace, check out OpenDeviceLab to see if a publicly-accessible collection of devices exists in your area.

7. Calling it a Day

Once satisfied with our work, coding these templates became no different from any other project. At Campaign Monitor, we use GitHub to commit our work and collaborate on any outstanding rendering issues, as well as loop in testing and design where required. If you haven't used GitHub before, readwrite has an excellent beginners' guide to get you started.

Admittedly, more often than not these steps would bleed into one another, or be repeated;  web and email coding and testing is seldom quick, clean or without incident. However, end results speak for themselves - a first batch of ten robust templates, delivered on time and now ready for everyone to use. Check out Canvas when you next need to send an email newsletter that looks great on mobile devices, as well as Gmail, Apple Mail and all the usual clients.

What You Can Learn From Our Workflow

Both the processes and tools used to create and collaborate with others didn't come to us in an instant - but given the multi-week timeline of the project and that we got to work on similar tasks repeatedly, we did have the benefit of being able to improve our workflow as we went along. Following this project, our recommendations to others are to:

Have a plan documented publicly.

The above steps were outlined in our internal wiki before work commenced; having this guide/specification accessible to everyone allowed new and remote staff to get up to speed very quickly, while giving other teams visibility over how the coders work. This document was refined as we went along, thus providing everyone with the latest information.

Look at how existing tools can be used in your workflow. 

While there's always the temptation to "shop around" for the latest and greatest when commencing a new project, forcing everyone to adopt unfamiliar apps can create unnecessary challenges. Talk to other teams about what they use to collaborate and see how they can be adapted for your own tasks.

Take the time to scope out a design. 

In both email and web projects alike, there can be disconnects in what designers, marketing teams, sales and others think is possible and what can be done as a coder… Especially when there are deadlines to meet. Take the time to conduct your own discovery and set expectations - spending a few extra days experimenting and discussing tasks is always better than missing an important milestone, or under-delivering!

Testing doesn't just happen in your favorite browser. 

How does your design look on Android devices? Even if you don't use one personally to browse, 33% of the US does - and this percentage is much higher elsewhere. The more platforms you can test on, the better.

To Sum Up

So, while there may be big differences between how email and web work is coded and produced, the steps required to bring a designer's vision to life are just as relevant. Hopefully our experiences will help you formulate a plan for your next code project, as well as ensure your team remains happy and productive when collaborating together.

August 26, 2014

“Outside In” — Ordering CSS Properties by Importance

This article is all about CSS code structure - specifically about a method I've been using for the last few years to bring some logic and consistency to the order in which I write my CSS. It’s a method I call “Outside In”.

Declaration Order?

I've heard of various approaches to writing CSS in the past. Some people don't use any particular order at all, others alphabetise declarations by property name, I've even heard of a handful of cases where some order them visually by the length of each property:value pair! 

A past poll on CSS-Tricks asked this question with a result that I found quite surprising: 39% of over 11,000 people have no specific plan when it comes to ordering CSS.

How do you order your CSS properties
How do you order your CSS properties? Total Voters: 11,093

Grouping by type might suggest height being next to width. Alphabetically would see declarations listed from background through to z-index, for example.

I use the method of grouping properties by type - although I even use a specific order for ordering by group!

With the exception of the “random method”, there is some degree of order in all of the other approaches. But that order doesn't necessarily map well to anything particularly useful regarding the styling of websites. 

If you were collecting data about the height of students in a classroom, ordering them by a length measurement makes sense. If you're categorising a collection of DVDs, alphabetical ordering might make sense.  But would CSS properties ordered in these ways have anything to do with their order of importance when those styles are painted by the browser? 

If ordering alphabetically, is an element's color more important than its width? Is an element's border-style more important than whether or not it's in the normal flow of the document? I'd say not.

Outside In

The method that I’ve come to love orders CSS properties by how much impact they have on the selected elements or other elements around them. The gist of the technique is to start with big-picture properties which impact stuff outside the element and work in towards the finer details. This is why I call it the “Outside In” method.

position and float declarations remove elements from their normal flow and have a huge impact on other elements around them. This is something important and I feel it should be made clear right at the top of a block of CSS. 

Controlling things like the cursor or overflow of an element are (usually) less important and therefore I tend to leave things like this towards the end. 

The order I use is as follows: 

  • Layout Properties (position, float, clear, display)
  • Box Model Properties (width, height, margin, padding)
  • Visual Properties (color, background, border, box-shadow)
  • Typography Properties (font-size, font-family, text-align, text-transform)
  • Misc Properties (cursor, overflow, z-index)

I know that border is a box-model property and z-index is related to position, but this order works for me. Even though I don't like alphabetical ordering, there's something that just feels right about putting z-index at the end...

Practical Example

Let's take the example of styling a button module. 

Let's start with a nice, meaningful class name like .button. I personally dislike contracted names like .btn and tend to favour long, descriptive class names where possible - it's just a personal preference, YMMV :)

/* <a href="#" class="button">Order now &rarr;</a> */
.button { }

We want to be able to manipulate vertical spacing around the button so will need to change the display from inline (the default for anchor links) to inline-block

To allow the button to grow in width depending on the text content, inline-block is a more flexible choice than float with a width set.

.button {
    display:inline-block;
}

Next, we'll need to add some box-model characteristics like margin and padding. Margin goes outside the box so, going “Outside In”, this should come first.

.button {
    display:inline-block;
    margin:1em 0;
    padding:1em 4em;
}

The next things to add are the colours. To separate out each group of property types, I like to leave a blank line - this makes each section stand out a lot more.

.button {
    display:inline-block;
    margin:1em 0;
    padding:0.5em 3em;

    color:#fff;
    background:#196e76;
}

Next we can add in the borders and shadows to provide some depth, followed by any typography properties, again separated by a blank line.

.button {
    display:inline-block;
    margin:1em 0;
    padding:1em 4em;

    color:#fff;
    background:#196e76;
    border:0.25em solid #196e76;
    box-shadow:inset 0.25em 0.25em 0.5em rgba(0,0,0,0.3), 
               0.5em 0.5em 0 #444;

    font-size:3em;
    font-family:Avenir, Helvetica, Arial, sans-serif;
    text-align:center;
    text-transform:uppercase;
    text-decoration:none;
}

Reading Code

One benefit of having a system like this is that it removes the need to think too much once it's been implemented. If I'm reading through my code and want to change something big-picture like an element's width or position, I know I'll be looking towards the top of a rule.  If I want to adjust something like text-transform or list-style, I'll be looking towards the bottom of the block.

Having the code structured like this is also really hand for others reading the CSS; if faced with code organised like this, it's very easy to see all the component parts that make up a button module. When writing code, it's important to make it as easy as possible to our fellow developers to read; this makes code easier to understand and maintain.

Preprocessors

I've used vanilla CSS to explain my methods here, but you can apply the “Outside In” approach just as effectively in your Sass, LESS and Stylus.

Conclusion

Coding can be a very personal thing. If you use a different method for organising your CSS, it would be great to hear about it! Leave a comment to continue the discussion.