CSS Selectors

Dr. Greg Bernstein

Updated February 5th, 2021

More CSS Selectors

Learning Objectives

  • Learn about how to make more targeted selections (combinators)
  • Learn how to select/style elements in particular states (psuedo-classes)
  • Learn how to add special “stuff” via CSS and pseudo-elements.
  • Learn how to select stuff based on HTML attributes

Readings

  1. Combinators

  2. Pseudo-classes and pseudo-elements. Go over a few of these like hover.

  3. Attribute Selectors. Just a bit.

Additional Selector Types

  • Combinators: … ways of combining two or more selectors in useful ways for very specific selections.
  • Pseudo-classes: Match one or more elements that exist in a certain state,
  • Pseudo-elements: Match one or more parts of content that are in a certain position in relation to an element.
  • Attribute selectors: Match one or more elements based on their attributes/attribute values.

Combinators

Descendent and Siblings

  • Descendent selector use a space between any two selectors
  • Child (immediate) selector use a > between two selectors
  • Adjacent Sibling selector use a + between two selectors
  • General Sibling selector use a ~ between two selectors

Descendent Example HTML

From MDN

<section>
  <h2>Heading 1</h2>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <div>
    <h2>Heading 2</h2>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
  </div>
</section>

Descendent Example CSS

From MDN

section p { /* descendent */
  color: blue;
}

section > p { /* child */
  background-color: yellow;
}

h2 + p { /* direct sibling */
  text-transform: uppercase;
}

h2 ~ p { /* any sibling */
  border: 1px dashed black;
}

Descendent Rendering

See Combinator1.html file.

More Combinators

  • AB Any element matching both A and B at the same time.

  • Example:

section.answer {
    border-style: solid;
    border-width: 2px;
    border-color: darkmagenta;
}

AB Example HTML

<li>Short Problem Description <span class="points">point value</span>
    <p>What can we put within a <em>list item</em> element?</p>
    <section class="answer">
        <p>Students answer here. If short answer just put in a sincle paragraph element.
        If longer answer put in a section element. In either case students should add
        a <em>answer</em> class attribute to the element used.</p>
    </section>
</li>

<li>Another Short Problem Description <span class="points">point value</span>
    <p>General problem instructions and such... A bunch of sub-questions follows.</p>
    <ol type="a">
        <li>Another sub-question
        </li>
        <li>A third sub-question
            <p class="answer">Here is the answer. Note that it is in its
            own paragraph element within the list item element.</p>
        </li>
    </ol>
</li>

AB Rendering

Matching element and class

Multiple Selectors

  • You can have multiple selectors apply the same rule.
  • Just separate the selectors by a comma “,”
  • Example
h1, h2, h3, h4, h5, h6 {
  font-family: helvetica, 'sans serif';
}

Testing Selectors from the Console

We can test a fair amount of selectors/combinators from the JavaScript console via the DOM

  • Example: document.querySelectorAll("p") will select and return an array of all the paragraph elements in the document.

  • In general use document.querySelectorAll(YOUR_SELECTOR). Very useful for debugging CSS!

Pseudo Classes

Pseudo Classes Defined

From MDN:

A CSS pseudo-class is a keyword preceded by a colon (:) that is added on to the end of selectors to specify that you want to style the selected elements only when they are in certain state.

There are three general cases: user feedback, state related, and special relations.

User Feedback

:focus is applied when an element has received focus, either from the user selecting it with the use of a keyboard or by activating with the mouse

:hover matches when the user designates an element with a pointing device, but does not necessarily activate it.

:active matches when an element is being activated by the user. It allows the page to give a feedback that the activation has been detected by the browser.

Hover Examples Live

This is a special Paragraph.

A secret Message

Code the Web!

HTML for Hover Example

<p id="MySpecialP">This is a special Paragraph.</p>
<div id="HovTarg"><p>A secret Message</p>
<p class="secret">Code the Web!<p>
<div>

CSS for Hover Example

We have not learned about these properties yet!

#MySpecialP:hover
{background-color: blue; color: white}

.secret {display: none}
#HovTarg {position: relative}
#HovTarg:hover p.secret {
  position: absolute;
  padding: 1em;
  top: -2em; left: 0em;
  height: 2em;  width: 10em;
  border: solid black;
  background-color: yellow;
  display: block;
}

Example :valid

<style>
    #MyMail {font-size: 40pt;}
    #MyMail:valid {background-color: lightgreen;}
    #MyMail:invalid {background-color: red}
</style>
<input id="MyMail" type="email">

Example :valid rendered

Special Relations

  • :first-child, :last-child, :nth-child()

  • The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n.

Example Tiger Stripes (CSS)

<style>
    #Tiger p:nth-child(2n+1) {background-color: gray;}
    #Tiger p:nth-child(2n) {background-color: lightblue;}</style>
<div id="Tiger">
    <p>One</p>
    <p>Two</p>
    <p>Three</p>
    <p>Four</p>
</div>

Example Tiger Stripes Rendered

One

Two

Three

Four

Pseudo Elements

Pseudo-elements

From MDN:

Pseudo-elements are very much like pseudo-classes, but they have differences. They are keywords — this time preceded by two colons (::) — that can be added to the end of selectors to select a certain part of an element.

Pseudo-elements (cont.)

  • ::after, ::before: Great for adding special content after the fact

  • ::first-letter, ::first-line: Good for special decorations and such

  • ::selection, ::backdrop: Have not used these

::before and ::after Example

<div id="BeforeAfter">
    <style>
        span.Sly {color:#adadad;}
        span.Sly::before {content: "[[";}
        span.Sly::after {content: "]]";}</style>
<p>A paragraph <span class="Sly">yes, it is a paragraph</span>
to demonstrate
<span class="Sly">why else would it be here</span>
the use of before and after.
</p>
</div>

::before and ::after Example Rendered

A paragraph yes, it is a paragraph to demonstrate why else would it be here the use of before and after.

first-letter, first-line Example

<div>
    <style>
    #A::first-letter {font-size: 2em; font-style:bold}
    #B::first-line {font-style:italic; font-weight:bold;}
    </style>
    <p id="A">A long, long time ago...</p>
    <p id="B">In a galaxy, <br>
        far, far, away <br>
        there was code!</p>
</div>

first-letter, first-line Live

A long, long time ago…

In a galaxy,
far, far, away
there was code!

Another first-letter Example

A long time ago in a …

Beam me up Scotty…

Another First Letter Example (html)

HTML:

<p class="flEx">A long time ago in a ...</p>
<p class="flEx">Beam me up Scotty...</p>

Another First Letter Example (CSS)

CSS:

.flEx::first-letter
{
  font-size: larger;
  color:blue;
}

Attribute Selectors

What are they?

From MDN:

Attribute selectors will match elements based on their attributes and attribute values. Their generic syntax consists of square brackets ([]) containing an attribute name followed by an optional condition to match against the value of the attribute.

Syntax

  • [attr] : Selects all elements with the attribute attr, whatever its value.
  • [attr=val] : Selects all elements with the attribute attr equal to val.
  • [attr~=val]: Selects all elements with the attribute attr, but only if the value val is one of a space-separated list of values contained in attr’s value.

Digression: data attributes

See using data attributes

Any attribute on any element whose attribute name starts with data- is a data attribute. You can make up your own!

<ol id="Choices">
    <li>p</li>
    <li data-answer="true">li</li>
    <li>section</li>
    <li>a</li>
</ol>

Substring attribute selectors

Niffty substring stuff!

  • [attr|=val] : select all elements with the attribute attr for which the value is exactly val or starts with val-
  • [attr^=val] : Selects all elements with the attribute attr for which the value starts with val.
  • [attr$=val] : Selects all elements with the attribute attr for which the value ends with val.
  • And more…
// reveal.js plugins