CSS Syntax
CSS is based on selectors and properties. You first provide your selector, this is the element you wish to apply the style to. You then use curly brackets { and insert your properties followed by a semi-colon and ending bracket }. The example below would set the font size to all <p> elements to 12px.
p {font-size:12px;}
Output
Selectors
Selectors are the elements you want to apply the style to. There are different types of selectors:
Type | Description | Example |
---|---|---|
Universal Selector | This matches any element. | *{margin-top:10px;} |
Type Selectors
|
These are selectors referring directly to HTML elements such as p, h1, b, I, u. | h3 {color:#333;} |
Descendant Selector | These are selectors which are descendant elements; for example in a paragraph tag you might want the <strong> element to appear in all upper case so the selector would be p strong. | p strong {text-transform:uppercase;} |
Attribute Selector | You can style an element by its attribute value; for example for the <input> element you might want a default width and height for textboxes. | Input[type=”text”] |
Pseudo-Classes | Lastly these are available on certain user actions such as hover and active. These will be explained in the links tutorial. | a:hover {text-decoration:none;} |
Properties
Properties are the style you want to apply to an element. For example you might want to change the background color, font, or font size. As seen above, the property comes in pairs with a name and value. The value is separated by a colon : then your value and then semi-colon ;. There are many properties available; some only apply to certain elements while others can be used on all elements. We will go through the properties in the next tutorials.
Comments
Comments in CSS start with a forward slash and then an asterisk /* and end in the reverse */.
/* This is a CSS comment! */
Linking CSS
To link a CSS sheet in an HTML document, in the <head> tag of the HTML document you type:
<link rel="stylesheet" type="text/css" href="URL to style sheet" />
You can also have the CSS in the HTML document. In the <head> tag put:
<style type="text/css"> </style>
It is now recommend that all styles should be in a separate style sheet. This will help you maintain your styles and will also load pages faster, since the HTML page requested will not be a big file.