Search code examples
csslayoutstructurestylesheet

Best way to structure a CSS stylesheet


I am relatively new to CSS and yet I seem to have got the language reasonably well for a newbie. However, whilst many of the tutorials I have read often warn about "organising and structuring your stylesheet properly" (and I can certainly see why now I have created some rather long stylesheets myself) I cant for the life of me find any info about a standardised format for a styleheet or a logical pattern for layout that makes later human reading easy.

For example, do I create a comment-bracketed section for each "geographical" section of my page (header, row1, row2, article1 etc) and keep all styles for that section within those comment borders? The problem seems when I have styles that get re-used in other sections - and putting them under a section for page-wide styles then negates the purpose of grouping them by section at all. Likewise, structuring my stylesheet by grouping based on text styles, layout styles etc seems even more confusing.

Is there a "good practice"? I know this sounds dumb but it seems no matter what you do with HTML and CSS somebody is ready to tell you its wrong, bad practice or unsemantic and I'm left confused. I want my code to be a good example of my work in case an employer wants to check it in future.


Solution

  • I've never been actually taught, however I can let you know how I organise my CSS documents. As you say, I like to divide it up into "geographical" areas... i.e. the rules that apply to the header, the side bars, the main content, the footer, etc. And then, below these I add very specific rules, say if I need to style a form or a table on a particular page. Finally I add a "General Gubbins" section at the bottom when I add generic rules that may apply across the board.

    Oh yes, I also like to add the designer's palette to the top for quick reference.

    For example...

    /*
    PALETTE:
    dark grey : #555555;
    pink      : #d93575;
    */
    
    /* HEADER */
    #header {...}
    #header ul {...}
    
    /* SIDE BAR */
    #side {...}
    #side ul {....}
    
    /* CONTENT */
    #content{...}
    #content p {....}
    
    /* FOOTER */
    #footer{...}
    #footer div {....}
    
    /* FORMS */
    form {...}
    input {...}
    
    /* GENERAL GUBBINS */
    .center {...}
    strong {...}
    floatleft {...}