CSS Selectors
For this activity, we will create and style a list (or multiple lists) of items (<li>
) of any kinds of contents. The list may be an unordered list (<ul>
) or an ordered list (<ol>
).
You are strongly encouraged to style the list as you wish; get creative and have fun! For example, choose a background color, change the font family / size / style / weight / color, adjust paddings, or try new properies and see how they look on your screen.
You may define and embed CSS rules in the document header or in a separate .css
file. For additional references, please refer to W3 Schools and Prof. Praphamontripong’s HTML Reference and CSS Reference.
To get started, create an HTML file.
- Add a list of items (either an unordered list or an ordered list, you decide and be creative). You will decide on the items; they may be textual content, links, images, emoji, etc. For example:
<ul> <li>item 1</li> <li>item 2</li> <li>item 3 — <a href="http://www.cs.virginia.edu/" target="_blank">link to CS department</a> </li> <li>item 4</li> <li>item 5 😜</li> <li>item 6</li> <li>item 7</li> <li>item 8</li> <li>item 9</li> </ul>
- Open your HTML file in a web browser. Observe how the document is displayed.
Next, we will examine how different CSS selectors affect the display of the page. For each of the snippets of CSS below, copy them into your page and notice which elements are selected.
- Define CSS rules to style the list items using element selectors (
ul
andli
).ul { font-family: Arial, Helvetica, sans-serif; margin: 10px; } li { display: block; padding: 4px 10px 4px 10px; }
- Define CSS rules to style the odd list items with
:nth-child
pseudo-class selector, and use theodd
keyword.li:nth-child(odd) { background-color: deepskyblue; color: white; font-weight: bold; }
- Let’s style the seleced item(s). Add a selected class to the 5th item with
class="selected"
.<li class="selected">item 5 😜</li>
- Define rules for the
.selected
class selector.li.selected { background-color: orange; }
Question: notice that
li.selected
overrides the striped effect previously defined inli:nth-child(odd)
. Why? - Style the odd list items after the selected item using the general sibling (i.e.,
all-next-siblings
) combinator. For example,li.selected ~ li:nth-child(odd) { background-color: gray; }
Try arranging
li.selected
beforeli:nth-child(odd)
and observe how the list is displayed.li.selected { background-color: orange; } li:nth-child(odd) { background-color: deepskyblue; color: white; font-weight: bold; }
Observe how the document display changes. Do this screen and the screen from the previous step look the same? If they are different, why?