Lecture 13: Introduction to CSS
Overview:
- What is CSS?
- Syntax and Terminology
- Grouping Selectors
- Contextual Selectors
- Embedded CSS
- Hiding CSS from Non-Supportive Browsers
- font-family Property
- Sizing Units
- color Property
- Updating to XHTML 1.0 Strict
- Validating Your CSS
What is CSS?
- CSS (Cascading Style Sheets) is a language that is intended to be used in conjunction with (X)HTML and other structured document formats, such as XML.
- CSS is entirely about presentation of information and is not concerned with its structure. Structure is entirely controlled by (X)HTML.
Syntax and Terminology
- Each instruction for a given tag or tags in CSS is referred to as a rule. The following is a rule:
h1 {font-size: 16px;} - Content in every <h1> tag in your document should now be 16 pixels tall.
- Each rule contains selectors and declarations. Selectors specify what will be affected by the CSS; declarations specify what the presentation will be. In the prior example these are:
Selector:
h1
Declaration:font-size: 16px - The declaration breaks down further, into property: value pairs. In the prior example these are:
Property:
font-size
Value:16px CSS Syntax:
- The declarations are always inside a single set of curly braces:
{ } - Follow each property with a colon.
- If there are two (or more) words in a property name, they are always separated by hyphens.
- Follow every declaration with a semicolon, as that indicates the end of one and the beginning of the next. While it is technically not necessary to include a semicolon if only one declaration is given, it is good coding style to still supply the semicolon, to prevent potential issues when styles are added down the road (future coders maintaining your code will appreciate it).
- The declarations are always inside a single set of curly braces:
- Any tag that is valid within <body> (including <body> itself) can be used as a selector. As long as the browser recognizes the tag (and it is located inside <body>), it should respond to CSS.
- Multiple property: value pairs can be specified; there is no limit to this.
Grouping Selectors
- The example given previously involved just one selector (h1), but what if you wanted to apply the same declaration(s) to more than one selector?
- The solution is to separate the selectors with commas. Each comma instructs the device reading the styles that another selector is being specified that will also use the declaration(s).
- In this example both <p> and <td> are being told to render their content at a size of 12 pixels:
p, td {font-size: 12px;} - This is more streamlined and efficient than the following (the two code examples have the same effect):
p {font-size: 12px;} td {font-size: 12px;} Sequence of the selectors makes no difference. It could be:
p, td {font-size: 12px;}or:
td, p {font-size: 12px;}
Contextual Selectors
- A contextual selector is one that will only come into effect when a specific pattern of nesting tags is followed.
- What creates the context is the use of a space between the selectors. The space indicates that the next element is a descendant or child of the previous element.
- Consider this example:
td p {font-size: 12px;} - Only text that is inside a paragraph, which is itself inside a table data cell, will be 12 pixels in size.
<td> This text is inside a td but is not inside a paragraph so it does not use the CSS. <p>This text is inside a paragraph that is also inside a td, so it uses the CSS.</p> </td>
- What you are really styling in a contextual setup is the content inside the very last selector (the one furthest to the right). The other selectors just set up the necessary context for that last selector.
- Why use contextual selectors? They allow us to pinpoint changes to specific areas of a document, rather than applying styles to every instance of a particular element. Assuming that your document is structured properly, these can be extremely useful.
- You can also have selectors that involve grouping as well as contextualization (because CSS is extremely flexible). Where would the following font size be applied?
div p strong em, div blockquote a {font-size: 12px;} - Important: Contextual selectors do not require that the indicated tags be nested immediately within each other (a parent-child relationship), although that works. As long as the nesting occurs somewhere along the line (a descendant relationship), the CSS will work. Of course, the nesting must follow the indicated sequence or nothing will happen.
Embedded CSS
- There are multiple ways of associating CSS with an (X)HTML document. The easiest one to start with when learning CSS is the embedded approach.
- Embedded CSS is placed entirely within the <head> </head> of the (X)HTML document.
- The CSS is surrounded by <style> </style> tags, which have a type attribute set to a value of "text/css" (to identify the style information as CSS), as shown in this example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Embedded CSS: Example 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body {font-size: 13px;}
h1 {font-size: 18px;}
</style>
</head>
<body>
<h1>A Sample Level 1 Heading, Sized at 18 Pixels</h1>
Some content, sized at 13 pixels because it is using the 'body' settings.
</body>
</html>
Hiding CSS from Non-Supportive Browsers
- One approach to hiding your embedded styles from very old browsers is to put the CSS instructions inside an (X)HTML comment:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Embedded CSS: Example 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css"><!--
body {font-size: 13px;}
h1 {font-size: 18px;}
--></style>
</head>
<body>
<h1>A Sample Level 1 Heading, Sized at 18 Pixels</h1>
Some content, sized at 13 pixels because it is using the 'body' settings.
</body>
</html>
- Since browsers ignore tags that they do not understand, old browsers (for example, version 3 browsers) would ignore the <style> </style> tags and would treat all the CSS rules as plain text, which would then output as the first lines of text at the top of the browser window.
- Those old browsers, however, do understand comments and so they would assume all the CSS was a comment and would not render it as text on the page. This behavior would hopefully generalize to all devices that are not CSS-aware.
- CSS-aware devices ignore the comments because they are (X)HTML comments in an area designated for CSS.
- CSS comments are enclosed in /* */, which distinguishes them from the <!-- --> (X)HTML comments
/* This is a sample CSS comment */
- The above approach gets you into trouble, however, if your XHTML code is sent through an XML parser. The XML parser uses the same setup for comments as (X)HTML and it would ignore all the CSS rules inside <!-- -->. To resolve this issue you can either remove the (X)HTML comments entirely or designate them as being character data (located inside <![CDATA[ ]]>), which is ignored by the parser:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Embedded CSS: Example 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css"><![CDATA[
body {font-size: 13px;}
h1 {font-size: 18px;}
]]></style>
</head>
<body>
<h1>A Sample Level 1 Heading, Sized at 18 Pixels</h1>
Some content, sized at 13 pixels because it is using the 'body' settings.
</body>
</html>
- The CDATA approach is necessary if your code contains <, >, or any other character in your CSS that needs to be specially encoded to work properly in XML.
- So which approach should be used? Currently most browsers are served XHTML files using the text/html mime type, rather than the application/xhtml+xml mime type, because the latter causes a variety of issues.
With text/html the (X)HTML comments are fine, with application/xhtml+xml CDATA is necessary if there are certain characters used and (X)HTML comments should be avoided around your CSS.
- These considerations only arise with embedded CSS; no other approach to implementing CSS encounters these issues.
font-family Property
- The font-family property specifies what fonts should be applied to content.
- Think of these as suggested fonts, because if the user's computer / handheld device / cell phone / etc. does not have the specified font, then you will get the default font instead.
- Fonts are separated by commas.
- Fonts with multiple words in their name should be surrounded by either single or double quotes (e.g., 'times new roman')
- The device reading the CSS starts with the first font in the sequence and tries to find a match. If that fails, it goes to the next font and tries to find a match. If that fails, on to the next font and the process is repeated until there is a match (in which case that font is used and the process stops) or none of the fonts match (at which point the default is used, which is usually a serif font of some sort).
- Typically I use this sequence:
font-family: verdana,geneva,lucida,arial,sans-serif;
All of these are sans-serif fonts, which are easier to read on computers given their lower ppi compared to print documents.
- verdana: Listed first, because this is the easiest to read (letterforms are large and the font was designed to be easy to read on computers). This is part of the Core Fonts that Microsoft installs along with Internet Explorer, so the vast majority of your users should have it installed. Mac OS X users will also have it installed.
- geneva: Found more prominently on Macs, this font is also easy to read. Many Windows computers will have this font installed too.
- lucida: This font can be found on some Linux installations, so those users will benefit.
- arial: This font is available on a wide variety of platforms, so it serves as a nice fallback.
- sans-serif: This is a generic font-family, which tells the browser to use whatever default font they have for that family. It is always good to specify a generic font-family last, as a truly last-ditch effort at getting some semblance of the desired rendering.
- If you are looking for an easy-to-read serif font I recommend georgia, which has large letterforms and is a Microsoft Core Font, so it should be pretty widespread. The generic font-family for serif fonts is, appropriately enough, serif.
font-family: georgia, serif;
- I recommend against choosing a rare font that only you and 5 other people in the world have. Sure, it looks great on your six computers, but for everyone else it just doesn't quite have the look you want!
- There are also monospace, fantasy, and cursive font-families, in case those need to be used. They are all generic font-families, like sans-serif and serif.
- Spelling also counts; you must match spelling exactly. Matching on capitalization is not necessary.
| Property | Usage and Effect | Values Accepted | Replaces | Recommendations |
|---|---|---|---|---|
| font-family | Specifies the font(s) to use for content, assuming that font is available. | font name | generic font family (sans-serif, serif, cursive, fantasy, monospace) | Deprecated <font> tag | Always specify a generic font-family last |
Sample code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Embedded CSS: Example 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css"><!--
body {font-size: 12px;
font-family: verdana,geneva,lucida,arial,sans-serif;}
h1 {font-size: 18px; font-family: georgia,serif;}
h2 {font-size: 16px; font-family: georgia,serif;}
--></style>
</head>
<body>
<h1>A Sample Level 1 Heading, Sized at 18 Pixels</h1>
<h2>A Sample Level 2 Heading, Sized at 16 Pixels</h2>
<p>Some sans-serif text, sized at 12 pixels because it is
inheriting the 'body' settings.</p>
</body>
</html>
Sizing Units
- Compared to (X)HTML, which is limited to generic sizes (1 to 7) for text and pixels or percentages for tables, CSS has a plethora of sizing options.
- Some of them (such as inches and picas) are not practical for text (or even for layout), so we will not be considering those sizing units.
- For the majority of CSS properties it is invalid to specify a number (e.g., 3) without specifying a unit along with it (e.g., px) and there is never a space between the number and the unit. The number 0, however, can always be supplied without a unit.
| Unit | Values Accepted | Advantages | Disadvantages | Recommendations |
|---|---|---|---|---|
| pixels | Number followed by px (e.g., 12px). | Renders consistently across browsers and platforms, because pixels are the basic unit of measurement for computer displays.
Mac IE 5.x, Windows/Mac Gecko-based browsers, and Windows/Mac Opera are able to resize text. |
Windows IE 5.x, 6, and 7 cannot resize pixels (although IE 7 has a page zooming capability).
Values below 10px can become illegible on some browsers and at high resolutions. Sometimes characters can look a bit distorted, because of difficulties fitting them into the desired number of pixels. |
Pixels can be your first choice, unless the inability to resize text will be an issue for your audience.
Sites with strict accessibility requirements should not use pixels for this reason. |
| points | Number followed by pt (e.g., 12pt). | Mac IE 5.x, Windows/Mac Gecko-based browsers, and Windows/Mac Opera are able to resize text. | No one agrees on how points translate into pixels, and web pages render on a grid of pixels. As a result, the text size rendered varies a bit cross-browser and cross-platform.
Windows IE 5.x, 6, and 7 cannot resize points (although IE 7 has a page zooming capability). Values below 8pt can become illegible on some browsers and at high resolutions. |
Points are best for print output (a topic covered in INP 170: Web Coding II).
Sites with strict accessibility requirements should not use points because of the inability to resize text in all browsers. |
| keywords | xx-small | x-small | small | medium | large | x-large | xx-large | Resizable in all modern browsers.
Rendering is consistent in modern browsers (except Windows IE 5.x), as long as they are set at the same size for their default ('medium' is equal to your default settings, so other keywords are relatively larger or smaller). IE 6 needs to be in Standards mode to work properly; in Quirks mode it behaves like Windows IE 5.x |
Limited choices available
Windows IE 5.x always renders text sizes one size smaller than specified, because it assumes 'small' is equal to your current browser default size, rather than 'medium'. IE 6 & 7 behave the same way if they render in Quirks mode. |
Always make sure your browser is rendering the code in a standards mode. A proper doctype is all that is necessary.
Test carefully to make sure sizes are not becoming too large. A valuable approach if accessibility is a high priority. |
| em | Number (decimal values are fine) followed by em (e.g., 1.2em) | Resizable in all modern browsers.
Rendering is consistent in modern browsers if the browsers are set at the same size for their default (1em is equal to your default browser settings, thus other em values are relatively larger or smaller). |
Text size is based on the parent element's size (the parent element is the tag holding the current element). Thus text can quickly grow very large or very small (and values below 1em, such as .8em, can become illegible). | Be extremely careful about specifying font sizes for multiple elements that could be nested.
Test carefully to make sure sizes are not becoming too large or too small. A valuable approach if accessibility is a high priority. |
| percentage | Number followed by % (e.g., 120%) | Resizable in all modern browsers.
Rendering is consistent in modern browsers if the browsers are set at the same size for their default (100% is equal to your default browser settings, thus other percentage values are relatively larger or smaller). |
Text size is based on the parent element's size (the parent element is the tag holding the current element). Thus text can quickly grow very large or very small (and values below 100%, such as 80%, can become illegible). | Be extremely careful about specifying font sizes for multiple elements that could be nested.
Since many browsers use a default text size of 16 pixels, you can set 'body' to 62.5% in order to give nested elements a starting size of 10 pixels. This makes subsequent math easier (120% would be 12 pixels). In general, browsers work best with percentages based on a multiple of ten (so 120% is preferable to 115%) Test carefully to make sure sizes are not becoming too large or too small. A valuable approach if accessibility is a high priority. |
Sample code for keywords sizing:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Embedded CSS: Keyword Sizing</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css"><!--
body {font-family: verdana,geneva,lucida,arial,sans-serif;}
span {font-size: x-small;}
h1 {font-size: xx-large; font-family: georgia,serif;}
h2 {font-size: x-large; font-family: georgia,serif;}
h3 {font-size: large; font-family: georgia,serif;}
--></style>
</head>
<body>
<h1>A Sample Level 1 Heading (XX Large)</h1>
<h2>A Sample Level 2 Heading (X Large)</h2>
<h3>A Sample Level 3 Heading (Large)</h3>
<p>Some sans-serif text at the default medium size,
except in Windows IE 5.x which defaults to small.</p>
<p>And then some <span>text that is x-small.</span></p>
</body>
</html>
Sample code for em sizing:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Embedded CSS: EM Sizing</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css"><!--
body {font-size: 1em;
font-family: verdana,geneva,lucida,arial,sans-serif;}
p {font-size: 1.5em;}
p span {font-size: 2em;}
div {font-size: .8em;}
div span {font-size: .6em;}
h1 {font-size: 2.5em;}
h2 {font-size: 2em;}
h3 {font-size: 1.5em;}
--></style>
</head>
<body>
<h1>A Sample Level 1 Heading (2.5em)</h1>
<h2>A Sample Level 2 Heading (2em)</h2>
<h3>A Sample Level 3 Heading (1.5em)</h3>
<p>Some text growing larger (1.5em)
<span>and larger (2em).</span></p>
<div>Some text shrinking (.8em)
<span>and shrinking (.6em).</span></div>
</body>
</html>
Sample code for percentage sizing:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Embedded CSS: Percentage Sizing</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css"><!--
body {font-size: 100%;
font-family: verdana,geneva,lucida,arial,sans-serif;}
p {font-size: 150%;}
p span {font-size: 200%;}
div {font-size: 80%;}
div span {font-size: 60%;}
h1 {font-size: 250%;}
h2 {font-size: 200%;}
h3 {font-size: 150%;}
--></style>
</head>
<body>
<h1>A Sample Level 1 Heading (250%)</h1>
<h2>A Sample Level 2 Heading (200%)</h2>
<h3>A Sample Level 3 Heading (150%)</h3>
<p>Some text growing larger (150%)
<span>and larger (200%).</span></p>
<div>Some text shrinking (80%)
<span>and shrinking (60%).</span></div>
</body>
</html>
color Property
- Colors are more flexible in CSS than in (X)HTML.
- While pre-defined color names and hexadecimal values are still supported, CSS allows a shorthand to be used for hexadecimal values.
The shorthand reduces a 6-character hexadecimal to a 3-character hexadecimal. For example #cccccc becomes #ccc and #ffffcc becomes #ffc. A value such as #4d4d4d, however, cannot use the shorthand.
- It is also possible to specify an RGB value in one of two fashions. An RGB value could be specified as a percentage of red/green/blue, such as: rgb(25%,50%,50%) or the red/green/blue can be specified from 0 to 255, such as: rgb(0,255,0)
| Property | Usage and Effect | Values Accepted | Replaces | Recommendations |
|---|---|---|---|---|
| color | Specifies the color to use for text inside an element. | One of the pre-defined color names, a hexadecimal value (e.g., #fff), or an rgb value: rgb(255,0,0) or rgb(0%,50%,25%) | Deprecated <font> tag | It is generally a good practice to have a background color specified along with the text color; a future lecture will explore background colors.
The CSS validator may give you warnings about not having a background color paired with a text color; you can ignore those warnings. Users associate blue text with links, so making unlinked text blue is bad for usability. |
Sample code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Embedded CSS: Colors</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css"><!--
body {font-size: 12px;
font-family: verdana,geneva,lucida,arial,sans-serif;
color: #4d4d4d;}
h1 {font-size: 18px; font-family: georgia,serif; color: purple;}
h2 {font-size: 16px; font-family: georgia,serif; color: green;}
--></style>
</head>
<body>
<h1>A Sample Level 1 Heading</h1>
<h2>A Sample Level 2 Heading</h2>
<p>Sample text</p>
</body>
</html>
Updating to XHTML 1.0 Strict
- Now that we are moving into CSS, we can stop using deprecated (X)HTML attributes that are related to presentation and switch from XHTML 1.0 Transitional to XHTML 1.0 Strict.
- The doctype to use is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- There is one other essential change that will need to occur in your coding: Strict requires that all content and all inline elements be inside a block-level container tag, such as a division, a paragraph, a table cell, etc.
Validating Your CSS
- The W3C has a validator for CSS at jigsaw.w3.org/css-validator/
- With embedded CSS the best approach might be to validate 'by direct Input'. Copy and paste just your CSS (not the <style> </style> tags, since that is (X)HTML and not CSS) into that textarea box and click the associated 'Check' button.