CSS Tips & Tricks

To Get You Started

Below you can find some CSS tips & tricks that have helped me along the way. If you would like me to add any here, feel free to email me at webmaster@louisrofrano.com.

  1. Use short hand where ever possible - I don't know how many times I have seen people using the code below, but it is very inefficient and can be rewritten into one line: .class {
         padding-left: 5px;
         padding-right: 0px;
         padding-top: 10px;
         padding-bottom: 0px;
    }
    You can write this using CSS short hand by doing the following: .class {
         padding: 10px 0px 0px 5px; }
    Doing this can save you 3 lines of code! You can also use CSS shorthand for background images, font declarations, margins, etc.
  2. Use Multiple Classes - In CSS, you can assign multiple classes to an element. This saves you the time of having to rewrite class to accomondate all of the styles. To do so, you can put all of your class names in the class definition, separated by a space.

    Lets say you have the following CSS: .link {
         color: #FF0000;
         font-weight: bold;
    }

    .noPadding {
         padding: 0px;
    }
    If you want to have a link that contains both of these classes, you would use the following code: < href="http://www.louisrofrano.com" class="link noPadding">louisrofrano.com<a>
  3. Always Define A Unit - CSS is very particular, especially when it comes to defining a unit. Whether it is px or pt or em, you must always define a unit (unless you are entering 0). For me, I even use a unit when entering 0 because it gets me into the habit of always following this tip.
  4. Center Align Fixed Width Block Element - Centering a block element that has a fixed width is much harder with CSS than it was with tables. No longer can we call align="center" and be done with it. To center align a fixed with block element you need the following code: body {
         text-align: center;
    }

    #ContentContainer {
         text-align: left;
         width: 400px;
         margin: 0 auto;
    }
    Your HTML would then be set up as follows: <html>
    <head>
    </head>
    <body>

    <div id="ContentContainer">>
         Content Goes Here (Centered)
    </div>

    </body>
    </html>
  5. Case Sensitivity - CSS classes and id's are case sensitive when you are creating an XHTML document. However, it is good practice to use a standard naming convention. I recommend making the first letter of the first word lowercase, and then every other first letter uppercase. I have no rhyme or reason for this, it just looks the most legible to me.

    If you do not match the class or id up exactly, the styles will not be applied when the document is displayed.

CSS

Ads