The Missing Semi-Colon

Image for The Missing Semi-Colon

So you think your CSS looks alright then? But it doesn't seem to do what I expect - what has happened to the margin on that div?

Look carefully; maybe you have missed out a semi-colon!

furthermore...

The Semicolon

In grammar, the semi-colon has some significance and also a history, but in CSS (and javascript, and PHP and  ... well any programming language), it terminates that line or block of rules and is required.

If you are writing CSS by hand (I mean not using a wysiwig editor like Dreamweaver), you really need approach the syntax rules with a significant amount of rigour. In CSS, each rule for the element needs to be terminated with a semi-colon (apart from the last one), so that the browser can move on to the read the next rule. So, in some CSS like this:

div.item {
border: 1px solid gray;
color:gray
margin:12px

the margin rule would not be delivered, because there is no semi-colon after the color:gray rule.

Technically, there is no need to place a semi-colon after the last rule, but, I usually do, because often, you might be coming back to edit the CSS and add further rules. The above would be corrected to:

div.item {
border: 1px solid gray;
color:gray;
margin:12px;

Formatting the CSS text

I prefer to layout the CSS with separate rules on each line (as above), but this little peice of CSS can be written thus:

div.item {border:1px solid gray;color:gray;margin:12px;}

When rules are applied inline then it is more likely that the rules are in one line like this:

<div class="item" style="border:1px solid gray;color:gray;margin:12px;">
some content here
</div> 

Other syntax gotchas

Then there are those pesky curly brackets; don't leave one out, because the chances are that the browser or eBook reader will not forgive you!

The curly bracket { opens the list of rules and then needs the matching closing bracket to close the list }.

When using the @media rule, you will need to nest the curly brackets like this:

@media only screen and (max-device-width: 480px) {
div#content {
width: 400px;
}
}

Posted on 09 Mar around 11am

Tags:

Commenting is no longer available in this channel entry.