Wednesday, July 20, 2011

how to override css classes

A useful trick when trying to write clean and unobtrusive css is the following: create id selectors. When you have a large and complex project with many css files flying around everywhere, and you want to override a class you should stop and think before you do. You should think "hey - is it possible that my changes might affect another component in a galaxy far far away (or maybe in my colleague's project)?" If the answer is yes, just create an id

#myId{
}

and within that id you can safely override that class you were so dying to override:

#myId .classWhichSucksSoMuchIWantToOverrideId{
   text-align:left;
}

RESULT:
In your code if you simply create an empty div like this

<div id="myId"> </div>

and inside that div you place all the code which corresponds to your part of the project like this:

<div id="myId">

   <div class="classWhichSucksSoMuchIWantToOverrideIt">
           this text will be left aligned!!
   </div>

</div>

you will see the overridden style applied only to the elements which are inside the outer div with id="myId".

Other, innocent elements which happened to have the class classWhichSucksSoMuchIWantToOverrideId will not be affected (unless they are inside the div with id="myId").

good job well done

No comments:

Post a Comment