How to organize CSS files

Hey guys and gals, I have been working on the responsive web design projects here on FreeCodeCamp. They have been a lot of fun, but I often find myself getting lost in the code (specifically CSS). Could anyone advise me or direct me to some resources where I could learn about the best practices of organizing code? I feel like my CSS files are a mess and would like to know how to make them more orderly and easier to follow.

You can look at some different css methodologies, a lot of them also involves using a CSS preprocessor. fCC has a section on using SASS/SCSS.

A few simple things you can do without breaking the CSS up into separate files/folders and using a preprocessor.

  1. Good class naming.

  2. Look at the page as being made up of individual parts, or components.

  3. Look at each component as being comprised of a main block and sub-elements that are part of that main block, name things accordingly.

Super simplified example, using no real convention:

.hero-section {
...
}

.hero-section-header {
...
}

.hero-section-image {
...
}

You get the point I’m sure.

  1. Order the CSS following the HTML source order as much as possible.

  2. Use comments in the CSS to delimit the start of a new block of related CSS.

/** Hero Section
 *  Some more info if needed
*/

It should also be noted that as much of front-end development has moved to frameworks/libraries like React and the like, CSS-in-JS has become more of a trend. Here the styles are (mostly) scoped to the component and all the styles are located by the “HTML” (the templating).

2 Likes

Thanks for the information! I’ll check it out! I’m looking forward to learning these frameworks and libraries in the future.

What also works well is using SMACSS.

It’s like writing modules for Javascript, just with css / sass. Also gives you the opportunity to build a decent folder structure for development.