What are the best practices for writing maintainable CSS?

后端 未结 9 1923
礼貌的吻别
礼貌的吻别 2021-02-06 04:25

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

9条回答
  •  余生分开走
    2021-02-06 04:58

    There's really no right or wrong answer here, certainly nothing definitive. Do what makes sense to you and is ideally most readable to others.

    Personally, I like to group related elements together, but I also organize them by the section in which they are located on the page. I will denote these sections with a comment in the CSS. For example, my header section may look like this:

    /* HEADER */
    
    #header {
        float:left;
        width:100%;
        height:162px;
        background:url(images/headerbg.gif);
        background-repeat:no-repeat;
    }
    
    #header-left {
        float:left;
        margin:0;
        padding:0;
        width:350px;
    }
    
    #header-right {
        float:right;
        margin:0;
        padding:0;
        width:620px;
    }
    
    #header a {
        color:#c4e6f2;
        text-decoration:none;
    }
    
    #header a:hover {
        color:#ffffff;
    }
    

    There's tons of different semantic practices surrounding CSS, but this is just an example of how I generally group my rules. I usually try to minimize the amount of CSS needed, so I use shorthands for borders, margins, padding, etc., and I try not to re-use CSS selectors. I group all properties together usually.

提交回复
热议问题