CSS selectors
Derek Bridge
Department of Computer Science,
University College Cork
CSS selectors
Aims:
- to review the syntax of CSS rules
- to review the hierarchical structure of (X)HTML
- to know the main CSS selectors
The evils of mixing structural and presentational markup
- Documents become bloated
- Class exercise: Why care? (At least two reasons)
- Presentation tags may be used in place of structural ones
- Class exercise: Does that matter?
Cascading Style Sheets (CSS)
h1 {color: red; background-color: blue;}
- A CSS stylesheet contains:
- one or more rules, and
- comments (written between /* and */)
- A rule comprises:
- one or more selectors
- one or more declarations
- A declaration comprises:
Attaching a stylesheet to an (X)HTML document
Advantages of CSS
- The (X)HTML document contains just content and structural markup, which
overcomes the problems mentioned earlier
- CSS is richer than the HTML presentational markup that it replaces
- Changes can be applied consistently
- to all elements affected by a rule
- to all the web pages in a web site
Simple selectors
- A selector can be a tag:
h1 {color: red;}
- We can have more than one selector:
h1, h2, em {color: red;}
- Or the universal selector:
* {color: red;}
Id selectors
- Revision of (X)HTML: the
id
attribute
- In CSS, you can use # to select by id:
#intro {color: red;}
- Class exercise: Sometimes people write the following. But why
are
*
and p
redundant here?
*#intro {color: red;}
and
p#intro {color: red;}
Class selectors
- Revision of (X)HTML: the
class
attribute
- In CSS, you can use . to select by class:
.fact {color: red;}
- Class exercise: Is
*
redundant here in general?
Is p
redundant here in general?
*.fact {color: red;}
and
p.fact {color.red;}
Descendant selectors
- Revision: the hierarchical structure
of an (X)HTML document
- To select
em
elements that are descendants of p
elements:
p em {color: red;}
- Class exercises:
- How would you select
strong
s that are
descendants of ul
s?
- How about
em
s that are descendants of strong
s and
strong
s that are descendants of li
s?
Dynamic pseudo-class selectors for hyperlinks
- To select a hyperlink that has not yet been visited:
a:link {color: blue;}
- To select a hyperlink to an already-visited address:
a:visited {color: red;}
- (Include such rules in this order due to a bug in some browsers)
-
Write a rule to select Zach's menu
- Write a rule to select "Zach's"
- It might be better if this document used
div
, span
,
id
and class
. Where and why?