CSS Best Practices  

Posted by ReelTym

CSS Best practice
  • Follow OOCSS (Object Oriented CSS), and DRY (Don’t Repeat Yourself) principles
  • Classes should not be named with the actual style it aims to display.  That defeats the purpose of using separating HTML for content and CSS for look and feel.  You will have tied the HTML to a specific look & feel.
    • Eg. class = ‘Blue-button’, or class = ‘width100’ are bad.
    • It should be something like class = ‘button’, or class = ‘primary-button’, and the colors and widths are put into the CSS.
  • The class should be used to specify the type of element it is.
    • Eg. Class = ‘search-result-row’  - all search result rows in the entire site has this class.
  • Objects or Identifiable Elements should be identified with an ID, which differentiates them from the elements with the same class.
    • Eg. ID = hotel-results or ID = flight-schedule-results, is the container that differentiates the different elements of class search-result-row

Example 1:

.header {width,font,etc}
.nav-button {style common across nav-button in header and footer}
#header-nav .nav-button {overrides for header .nav-button}
#footer-nav .nav-button {overrides for footer.nav-button}
.nav-button.selected {override for .nav-button for selected button}

<div ID=’header’>
<ul ID=’header-nav’ class=’navbar’>
<li ID=’nav-home’ class=’nav-button selected’>Home</li>
<li ID=’nav-hotel’ class=’nav-button’>Hotel</li>
<li ID=’nav-flight-schedule’ class=’nav-button’>Flight Schedules</li>

Example 2:

.search-results {styles for all search results lists in the site}
.search-result-row {style for all search results rows in the site}
#hotel-results .search-results {override for hotel specific search result}
#flight-schedule-results .search-results {override for flight schedule specific search result}
#hotel-result-1 .search-result-row {override for first row of hotel results}

<div ID=’hotel-results’ class=’search-results’>
                <div ID=’hotel-result-1’ class=’search-result-row’>
                                <span class=’vendor’>Silver Cloud</span>
                                <span class=’price’>$100</span>

<div ID=’flight-schedule-results’ class=’search-results’>
                <div ID=’flight-schedule-result-1’ class=’search-result-row’>
                                <span class=’vendor’>American Airlines</span>
                                <span class=’departure-time’>11:11 am</span>
                                <span class=’arrival-time’>12:12 pm</span>