Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices for writing maintainable CSS?

Tags:

css

I am just starting to explore this area and wonder what are the best practices when it comes to production of clean, well-structured and maintainable CSSes.

There seems to be few different approaches to structuring CSS rules.

One of the most commonly encountered ones I saw was throwing everything together in one rule, i.e. margins, borders, typefaces, backgrounds, something like this:

.my-class {
    border-top:1px solid #c9d7f1;
    font-size:1px;
    font-weight:normal;
    height:0;
    position:absolute;
    top:24px;
    width:100%;
}

Another approach I noticed employed grouping of properties, say text-related properties like font-size, typeface, emphasis etc goes into one rule, backgrounds go into other, borders/margins go into yet another one:

.my-class {
    border-top:1px solid #c9d7f1;
}

.my-class {
    font-size:1px;
    font-weight:normal;
}

.my-class {
    height:0;
    top:24px;
    width:100%;
    position:absolute;
}

I guess I am looking for a silver bullet here which I know I am not going to get, bet nevertheless - what are the best practices in this space?

like image 430
Art Avatar asked Jan 11 '11 00:01

Art


People also ask

What is better practices for writing including a CSS file?

For developers using a CSS preprocessor, the best practice is to write @extend rules first and @include rules second. The reason for that is the fact that you're aware right away that those styles are inserted into the selector, and you are able to easily override them below it.


1 Answers

I used an own order, convinient for me.

Rules there were listed in the descending order, and the criterion is rule's affect on the layout. For example:

.element {
    float:none;
    position:relative;
    top:-2px;
    z-index:100;
    width:100px;
    height:100px;
    margin:10px 0;
    padding:0;
    border:1px solid #000;
    background:#F00;
    font-size:10px;
    color:#CCC;
}

Of course, in the example above I didn't list all css instructions.

Particular idea was to keep order of groups, such as:

  1. Positioning
  2. Width and height
  3. Margins and paddings
  4. Borders (and others, affecting element's total dimensions)
  5. Backgrounds, aligning (and others, which don't affect whole page's layout)
  6. Typography
like image 192
Flack Avatar answered Sep 30 '22 20:09

Flack