CSS Architecture: CSS File Organization

Share this article

CSS Architecture: CSS File Organization

The following is an extract from our book, CSS Master, written by Tiffany Brown. Copies are sold in stores worldwide, or you can buy it in ebook form here.

CSS File Organization

Part of a good CSS architecture is file organization. A monolithic file is fine for solo developers or very small projects. For large projects—sites with multiple layouts and content types, or multiple brands under the same design umbrella—it’s smarter to use a modular approach and split your CSS across multiple files.

Splitting your CSS across files makes it easier to parcel tasks out to teams. One developer can work on typography-related styles, while another can focus on developing grid components. Teams can split work sensibly and increase overall productivity.

So what might a good file structure that splits the CSS across files look like? Here’s a structure similar to ones I’ve used in recent projects:

  • reset.css: reset and normalization styles; minimal color, border, or font-related declarations
  • typography.css: font faces, weights, line heights, sizes, and styles for headings and body text
  • layouts.css: styles that manage page layouts and segments, including grids
  • forms.css: styles for form controls and labels
  • lists.css: list-specific styles
  • tables.css: table-specific styles
  • carousel.css: styles required for carousel components
  • accordion.css: styles for accordion components

If you’re using a preprocessor, such as Sass or Less, you may also want to include a _config.scss or _config.less file that contains color variables and the like.

In this structure, each CSS file has a specific and narrow scope. How many files you’ll ultimately end up with depends on how many visual patterns or components are called for by your site’s design.

CSS frameworks such as Foundation and Bootstrap use this approach. Both become quite granular with separate files for progress bars, range inputs, close buttons, and tooltips. This allows developers to include only the components that they need for a project.

Note: Pattern Libraries

A closely related concept to splitting CSS across files like this is the pattern library. A great primer on the subject is Anna Debenham’s “Getting Started with Pattern Libraries.”

How many files?

Even though we’re using several CSS files for development, we’re not going to serve all of them to the browser in this form. The number of HTTP requests that we’d require would make our site take lonegr to load. Instead, we’ll concatenate our smaller CSS files into a few larger ones for production.

Concatenation in this context, means combining multiple files into a single CSS payload. It eliminates the need for @import statements or multiple link elements. Current browsers have limits on how many files they can download at once. We can use concatenation to reduce the number of network requests, getting your content to users in less time.

Often your web development framework will handle concatenation as part of its asset management features, such as Ruby on Rails. Some content management systems do the same, whether as a core feature or an add-on. Preprocessors—introduced in Chapter 9 also make concatenation easy. If neither preprocessors nor development frameworks are part of your workflow, chances are that your operating system has a concatenation utility that you can use instead.

For Mac OS X or Linux, concatenate files using the cat utility:

cat file1.css file2.css > combined-output-file.css

Using Windows? Try the type utility:

type file1.css file2.css > combined-output-file.css

You can also write your own concatenation script using Bash, PHP, Python, or another scripting language of your choice.

Note: CSS Optimization

Concatenation is one aspect of CSS optimization. It’s just as important to minify your files to remove excess characters and whitespace. Minification tools are covered in Chapter 3.

So how many files should you use? That’s where it gets tricky. The current best practice is to identify your critical path CSS—the minimum amount of CSS your page needs to render—and embed it in your pages using the style element. Additional CSS files should be loaded using JavaScript. Addy Osmani’s presentation “CSS Performance Tooling” provides an excellent overview of this technique and some tools you can use to implement it. Also see the Filament Group’s loadCSS.

If your content will be served using the SPDY or HTTP/2 protocols, concatenation may be unnecessary. With HTTP/1.1, browsers download assets sequentially; the next request begins when the previous one ends. Under that model, reducing the number of network requests improves site performance; however, SPDY and HTTP/2, can download multiple assets at once. As a result, there is no real benefit to reducing the number of requests. There is, however, a cost to sending more bytes than necessary to render the page. William Chan’s “HTTP/2 Considerations and Tradeoffs” explains this in greater detail. The best approach would be to identify if your server is serving HTTP/2 and, if so, check whether more of you users will benefit from actually splitting your assets down and only loading that which the page needs, or continuing to work in the old way. If you’re interested in learning more about performance optimization methods, the SitePoint book Lean Websites is a useful resource.

Frequently Asked Questions on CSS File Organization

What is the best way to structure my CSS files?

The best way to structure your CSS files largely depends on the size and complexity of your project. For smaller projects, a single CSS file might suffice. However, for larger projects, it’s advisable to split your CSS into multiple files. This can be done based on the component or page they style. For instance, you can have a separate CSS file for the header, footer, and main content. This makes your code easier to maintain and debug.

How can I keep my CSS code clean and organized?

Keeping your CSS code clean and organized is crucial for maintainability. You can achieve this by following a few best practices. First, use comments to describe what each section of your CSS does. Second, group related styles together. Third, use consistent naming conventions for your classes and IDs. Lastly, consider using a CSS preprocessor like Sass or Less to help manage your stylesheets.

What are CSS preprocessors and how can they help in organizing CSS files?

CSS preprocessors like Sass and Less are scripting languages that extend the capabilities of CSS. They allow you to use variables, nested rules, mixins, and functions, which can greatly simplify your CSS and make it easier to maintain. Preprocessors compile your code into standard CSS that browsers can understand.

How can I use CSS modules to organize my CSS?

CSS modules are a way to make your CSS more modular and reusable. With CSS modules, each component in your application has its own CSS file. This makes it easier to manage your styles, as changes to one component’s CSS won’t affect others. To use CSS modules, you’ll need a build tool like Webpack or Parcel.

What is the role of comments in CSS file organization?

Comments play a crucial role in CSS file organization. They help you and other developers understand what each section of your CSS does. This is especially important in large projects where you might have multiple CSS files. Comments can also be used to temporarily disable sections of your CSS during debugging.

How can I use CSS frameworks to organize my CSS?

CSS frameworks like Bootstrap and Foundation provide pre-written CSS that you can use to style your website. They also provide a consistent structure for your CSS, making it easier to maintain. However, keep in mind that using a CSS framework might add unnecessary bloat to your website if you’re not using most of its features.

What is the importance of consistent naming conventions in CSS?

Consistent naming conventions in CSS make your code easier to read and understand. They also make it easier to find specific styles when you need to update or debug your code. There are several naming conventions you can follow, such as BEM (Block, Element, Modifier), OOCSS (Object-Oriented CSS), and SMACSS (Scalable and Modular Architecture for CSS).

How can I use CSS variables to organize my CSS?

CSS variables, also known as custom properties, allow you to store specific values for reuse throughout your CSS. This can greatly simplify your CSS and make it easier to maintain. For instance, you can store your website’s primary color as a variable and use it wherever that color is needed.

What is the role of a CSS reset in CSS file organization?

A CSS reset is a set of styles that you apply at the beginning of your CSS to reset the default styles applied by browsers. This ensures that your website looks consistent across different browsers. A CSS reset can also make your CSS easier to manage, as you won’t have to override browser styles for each element.

How can I use CSS linting tools to keep my CSS organized?

CSS linting tools like Stylelint and CSSLint can help you keep your CSS organized by catching errors and enforcing consistent coding styles. They can be integrated into your development workflow to automatically check your CSS as you write it. This can help you write cleaner, more maintainable CSS.

Tiffany BrownTiffany Brown
View Author

Tiffany B. Brown is a freelance web developer and technical writer based in Los Angeles. Brown offers web development and consulting services to larger agencies and small businesses. A former member of the Opera Software developer relations team, Brown is also co-author of SitePoint's JumpStart HTML5 book. She sporadically writes about web development technology on her blog. You can follow her on Twitter at @webinista.

AdvancedCSSbookCSSexcerpt
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week