Monday, 4 February 2013

CSS Tips

I've been writing CSS for many, many years now and while there is a fairly basic understanding of the system to many web developers, there are a few things that some may not be familiar with.
For example…

Multiple targeting within a class attribute.

Most will be familiar with the concept of using a CSS class selector in html like so:
<div class="my-newclass">My Red Text...</div>
This can be referenced in CSS like so:
.my-newclass {
 color: red;
Thats fairly straight forward, and you can see the targeting concept. But what if you wanted to use another class in combination with currently applied class?

Lets say we had a green background style like so:
.my-green-background {
 background-color: green;
If we want to use this in combination with the previous class, we combine the two selector references within the html like so:
<div class="my-newclass my-green-background">My Red Text...</div>
Separating the two class references by a space allows for easy combination of styles and reduces the need for additional unnecessary CSS rules.

Multiple selectors with the same style rules.

If you want or need to add style settings for more than one id, class or element you can string them together within a CSS declaration like so.
h1, h2, h3, h4 {
 color: red;
Again, this allows a developer to drastically reduce the amount of rules, and can produce some very nice standardisation which is always helpful with web projects.

An !important style

Occasionally a developer will find themselves in a position where the cascading nature of the CSS rules can 'corner' a style into something that looks wrong. Of course, its always possibly to rewrite CSS rules to work around the problem, but with rule glitches that are at the end of a cascading line (i.e. they are not required to be changed further), its much easier to force the particular style setting.

That is where !important can become extremely useful, like so.
.my-new-class h1 {
 color: red !important;
In this example, wherever 'h1' appears within the scope of 'my-new-class', it will be red (unless there is another !important further up the CSS chain). While this is very useful, it should only ever be used sparingly and after other parent CSS rules have been looked at to see if it makes more logical sense to change it from there.

More info here:

No comments:

Post a Comment