Archive for the 'CSS' Category

Rendering styles

Wednesday, October 4th, 2006

The question is - what will a browser do, given a page with several stylesheets, each of them probably overwriting definitions from the previous ones? Will the browser render the page using the first received css file, while downloading the other ones and after that partially re-rendering where required? The answer is: no, the browser will wait until all CSS files are downloaded, (then probably merge all definitions, just a wild guess) and will render once.

Test

I did this test - one page with two stylesheets that contain pretty much the same selectors for different table styles (thanks to this gallery). Each of the CSS files is actually a PHP script and has a call to sleep(), one sleeps for 5 seconds, the other one for 10.

Result

The browser sits there and waits for the both styles, rendering nothing (except for the page title, but that's not really rendering, is it?). So nothing happens for 10 seconds, then the second style is used for the final rendering. This happens in both FF and IE.

Misc

I also tried sleeping in the actual page, and flushing the output after each row. In my home environment FF renders each row as it's received, but in my hosted environment, it waits for the whole table. IE alsways waits for the complete table.

If I put the page to too much sleep so that the php script dies before the second stylesheet is dowloaded, the browser uses whatever is at hand (css1) to render the page.

Demo/download

 

Parent’s styles in an iframe

Sunday, September 3rd, 2006

Here's a JavaScript that let's you style an iframe just like its top parent. The script is basically just a proof of concept I did after talking to a friend about similar problem he has had in the past, so feel free to modify and use if you like it.

So I have a page, called big.html and a stylesheet for this page, called big.css. On the page there is an iframe that loads small.html. small.html has its own style, called small.css. What my little Javascript function does is:

  1. Getting all top parent's <link> tags
  2. Looping through the tags and checking if the rel attribute has value stylesheet
  3. For all stylesheets found, makes a copy of the link tag and all its attributes and adds it to the head of the iframed page

Here's the code:

function styleMe() {
  if(window.top && window.top.location.href != document.location.href) {
  // I'm small but I'm not alone

    // all parent's <link>s
    var linkrels = window.top.document.getElementsByTagName('link');
    // my head
    var small_head = document.getElementsByTagName('head').item(0);
    // loop through parent's links
    for (var i = 0, max = linkrels.length; i < max; i++) {
      // are they stylesheets
      if (linkrels[i].rel && linkrels[i].rel == 'stylesheet') {
         // create new element and copy all attributes
        var thestyle = document.createElement('link');
        var attrib = linkrels[i].attributes;
        for (var j = 0, attribmax = attrib.length; j < attribmax; j++) {
          thestyle.setAttribute(attrib[j].nodeName, attrib[j].nodeValue);
        }

         // add the newly created element to the head
        small_head.appendChild(thestyle);

      }
    }

    // maybe, only maybe, here we should remove the kid's own styles...

  } else {
    alert('I hate to tell you that, but you are an orphant :(  ');
  }
}

To see the code in action, see big.html.

 

Opacity for the thumbs

Friday, May 5th, 2006

I've been just toying with the CSS opacity to make fancier image thumbnail rollovers, it's actually quite easy. The idea is when you have a thumbnail photo gallery to make the thumbs semi-transparent and, on mouse over, to remove the transparency and show the real image as is.

All it takes is this little piece of CSS:

a img {
    opacity: 0.55;
    filter:alpha(opacity=55);
}
a:hover img {
    opacity: 1;
    filter:alpha(opacity=100);
}

Here's a demo. CSS file is here.

The demo uses Y!API to get a few images (I never seem to have good images laying aroud when I need them). The API call gets JSON output from the Yahoo! search API to make it easy (and server-side free) to display the results. You may peek into the JS source if you're curious (more Y! JSON search API here), but doesn't have anything to do with the main purpose - the thumbs rollovers.

 

Curly underline

Tuesday, April 4th, 2006

Ever wanted to use un underline on a web page that looks like a spelling mistake in Word? You know, the curly red underline. It's actually very easy.

Here's an example.

All you need is:

  • A small piece of the wavy line, like this Curly underline (it's stretched here for the demo purpose)
  • A style that uses the image as background
  • Align the background at the bottom and repeat only on the x-axis

The style definition would look like:

.curly-underline {
    background: url(underline.gif) bottom repeat-x;
}

And that's it!

I saw this working in TinyMCE, the WYSIWYG editor used by WordPress, for displaying spelling mistakes. Really cool!

Note: If you're a frequent visitor to my site and the example doesn't work for you, chances are you're using a cached version of the CSS file.

 

CSS coding conventions

Friday, September 30th, 2005

Motivation

Why standards and conventions? Well, it makes the code more predictable. You know where to look when you need to change/debug something and also other coders can pick up easier if they know what conventions you followed. PHP (actually PEAR) has it, Java has it, but I couldn't find anything for CSS, so here are a few ideas.

The important thing to remember is - it's not that important what exactly is a chosen standard or convention, the most important is that there is one. The rest, the details, is just common sense, and since "the common sense is not common to everybody", pick whatever makes sense for you. Below is a suggestion to get you started and build upon.

By example

OK, here's everything this post is about, in a few lines, the rest is just elaborating on this:

.container-subcontainer-general-specific {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 1em;
}

Terminology

Before starting to talk about the coding style and conventions, let's quickly review what are the different terms used to describe the elements of the CSS puzzle.

selector {
    property: value;
}

The whole thing above is called "a style" or "a style definition". "Style name" may be used as a synonymous for "selector".
"Property-value pair" needs a better name.

Spacing

Generally spacing promotes readability, so let's take advantage of it.

Empty lines between style definitions

Allow the separate style definitions to breathe, by adding one (and only one) empty line between them, like:

.some-class {
    color: red;
}

.another-class {
   color: blue;

}

1 tab = 4 spaces

Indentation also helps with the readability of the code. So put every property-value pair on a new line and indent it with 4 spaces from the beginning of the line. You can use a tab for indentation, it doesn't matter, this is just a personal preference. To avoid hitting [space] 4 times, configure your editor to do it for you when you hit [tab]. Every half-decent text editor has this configurable (Notepad is not the best choice for a coding editor)

Space after colons

Visually emphasis on the separation between a property and value, by adding a space after the colon, like:

.class {
    prop: value;
}

... and not

.class {
    prop:value;
}

... or

.class {
    prop:      value;
}

Curly brackets

Curly brackets that embrace all property-value pairs in a style definition follow your favourite if-then-else style you'd use in other programming languages. The opening bracket may be on the same line as the selector identifier or it can go alone on the next line

.class-name {
    color: green;
}

or

.class-name
{
    color: green;
}

I personally prefer the first.

Shorthands

The use of shorthands is forbidden, because they are harder to read.I would advise against the use of shorthands, because (for a non-expert) they are harder to read. Again, like I said in the beginning, it's you who decide on the type of style to follow, so if the majority of your team is comfortable with shorthands, by all means, use them. But I think that in most cases, the use of shorthands would cause more troubles (will obfuscate the stylesheets) that outweighs their benefits (less bandwidth).
Consider:

.text {
    font: 1em/1.1em bold italic small-caps Verdana, Arial, Helvetica, sans-serif;
}

and

.text {
    font-size: 10em;
    line-height: 1.1em;
    font-weight: bold;
    font-style: italic;
    font-variant: small-caps;
    font-family: Verdana, Arial, Helvetica, sans-serif;
}

The border style is an exception from that rule, because short handing it is so widespread and because (unlike "font" and others) the order of its properties is not important. For example:

.some-div {
    border: 1px #ff0000 solid;
}

...is the same as...

.some-div {
    border: solid 1px #ff0000;

}

and is just as readable.

End of line

Good practice is to always end the lines (the property-value pairs) with semi-colon, even when not necessary (last pair in a selector). This way it's easier to add more properties later on, without even bothering to check if the previous property-value pair was properly terminated.

Naming selectors

  • The most important thing to have in mind is the content nature of the HTML document, not its presentation. Selector names should describe the content.
  • Avoid presentation-specific words in the name, like "blue", "text-gray", or "light-box". What happens when you decide to change the color? The class "blue" is actually red?
  • Cascade the name, using a dash (-) as a separator. When cascading, have in mind what the content is. What do I mean by cascading? For example: "header" and "header-logo" (you have a page header that contains a logo at, say, the top-left corner) or "footer" and "footer-copyright"
  • Use full descriptive words. Abbreviating a word may save you a few milliseconds to type initially, but may make your code harder to read, costing you more time down the road. Why crypting "product" to "prod" or the so common "txt" (just spell it out as it is, "text")? Being consistent in this will save you the time spent thinking (or trial-error-ing) how exactly you abbreviated a word five days ago. (OK, OK, there are exceptions, you can use "url" instead of "uniform-resource-locator" :D )
  • Names are lowercase. There are browser problems with case sensitivity, so you're safe always lowercasing.
  • Distinct words in the class name are separated by a dash. It's clear, readable and gives the underscore a well-deserved break. Use footer-copyright, not footer copyright, footerCopyright, FooterCopyRight, fOOtercopyRighT (god forbid!) or footer_copyright. Well, if you're attached (married ;) ) to the underscore, I guess it's OK to keep using it, but consider leaving it for your Javascript code. The dash is not allowed in other languages' variable names, so use it when you can (in CSS), plus it's somewhat consistent with the property names (think font-size, background-color, etc.)
  • Once again - use names that describe the content ("footer", "navigation", etc), rather than the presentation ("blue", "left", "big"...)

Font sizes

When possible, use em instead of pix for sizing fonts, line heights, etc. This allows your visitors to use the built-in browser text sizing, without you coding a special text size feature (which will probably limit the user to the choices you decide anyway).

Offtopic

Preferably use HTML tags to describe the content.

<h1 class="content-heading">I'm a heading</h1>

is better (semantically, for SEO, for the human reader) than

<span class="content-heading">I'm a heading</span>

Comments

We all love to read other people's code comments. Writing our own comments is probably not as fun, but is highly encouraged in the name of maintainability. When you comment, use the /* comment here */ style. Line comments (the ones with // at the beginning) are not part of the CSS2 standard and may cause issues in some browser (or alternatively used as a workaround hack for some browsers, but this is another story)

Conclusion

I can only hope this has inspired you to adopt a CSS coding style convention/standard in your daily work. I'd love to hear you opinion on this topic. Are you currently using a standard? Do you know of any available on the web?