Structured way to organize CSS code

2019-05-02 23:27发布

问题:

When building a relatively large website, the CSS structure ought to be properly scoped and organized right from the begininning. If no CSS framework is used then everything can be lumped together into a massive stylesheet, but this will very quickly get out of order and can become a huge maintenance liability.

For the past few years, I've broken my stylesheets into various files including: base.css, layout.css, fonts.css, elements.css, but very easily the style definitions can jump between files and this approach needs to be more strict. I haven't used a framework since I'm not a fan of preset columns and pre-defined elements in my CSS code.

What approaches, patterns or tips can you guys suggest for keeping things organized? What kinds of naming conventions, reusability practices and patterns are useful? Is this something that a framework should be used for?

回答1:

I used to love LESS, but now I'm a big fan of Stylus because I think it makes even cleaner code than LESS/SASS/CSS -- no semicolons, colons, or brackets.

Because Stylus (and LESS and SASS) allow you to define variables and templates and functions, I have the following files, which should be in this order:

  • reset - A Stylus version of Eric Meyer's CSS reset
  • variables - Variables like colors, fonts, etc.
  • templates - Templates like border-radius, transitions, and clearfix
  • Stylings for each page (homepage, app, terms of service, etc)

These are all concatenated and compiled to CSS using a simple build script.

You can see what these look like; I made a GitHub repo for this stuff.



回答2:

For writing consistent and manageable stylesheets CSS LESS Framework is very beneficial.
LESS provides the following mechanisms: variables, nesting, mixins, operators and functions for writing CSS codes dynamically and can run on the client-side (Internet Explorer 6+, WebKit, Firefox) and server-side, with Node.js or Rhino.

http://lesscss.org/



回答3:

Regarding Stylus — lack of semicolons, colons, and brackets makes your code less readable IMO, rather than moreso.