Styles are an important technique used to separate content and formatting (style). Styles can be added directly to a tag, inserted in a section at the top of the web page or included in a linked file.
Embedded into a tag
A style can also be embedded into the actual tag, for example:
Will display the paragraph in green
Paragraph one in green
Span is a generic inline container, and allows a style to be attached to specific words in text . Attributes allowed are id (replaces name from html 3.x), class, title, style, lang.
In this example the style changes the colour of the word world to red. The title tag gives a tool tip when the mouse hovers over the word world.
This is better handled by using an embeded style separated from the tag.
Note that the .tooltip can be assigned to all tags
Embedded style sheet
The style sheet is placed between the <style> and </style> tags placed after the <head> tag.
This style sheet defines the pages background and colour (body), as well as bold (b) and heading 1 (h1).
Linked Style sheet
This example assumes that page.css is kept in the css directory.
The CSS syntax is made up of three parts: a selector, a property and a value:
- The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon and surrounded by curly braces:
- If the value is multiple words, put quotes around the value:
- Note: If you wish to specify more than one property, each property is separated with a semi-colon. The example below shows how to define a center aligned paragraph, with a red text color:
- You can group selectors. Separate each selector with a comma. In the example below we have grouped all the header elements. Each header element will be green:
Contextual selectors are strings of two or more simple selectors separated by a space. These selectors can be assigned normal properties and, due to the rules of cascading order, they will take precedence over simple selectors. For example, the contextual selector in:
is p strong. This rule says that strongly emphasized text within a paragraph should have a yellow background; strong text in a heading would be unaffected.
Comments in CSS
- You can insert comments in CSS to explain your code, which can help you when you edit the source code at a later date. A comment will be ignored by the browser. A CSS comment begins with "/*", and ends with "*/", like this:
Note: There is no "line comment" as there is in C/Java like languages (e.g. "//") so for a line you must use