CSS banner image.

In the post Starting simple CSS I left off with a basic CSS rule. Your formatting requirements will quickly require you to add to your CSS skills to achieve your design. To do this we need to understand the role of selectors a little better: think of CSS selectors as the “hooks” or “markers” that you use when applying CSS. The selectors identify where the CSS rules must be applied. They range from very simple to quite complex!

In this post:

  1. Simple
    1. Group
  2. Not so simple
    1. Chaining
    2. Pseudo class

1. Simple

Any HTML element can be used as a selector. If you want all of your paragraph text to be formatted in a specific way, then you can simply use p as your selector.

If you want to be more specific, you can use classes and/or id’s. Many elements in a page can have the same class. Only one element of each kind can have a specific id.

/* all paragraphs must be Arial font */

p {
    font-family: Arial;
}

/* all paragraphs with the class warning-text must have bold red text
   these paragraphs will also be in Arial font due to the previous rule which also applies */

p.warning-text {
    color: red;
    font-weight: bold;
}

/* all paragraphs with the id author-info should have a solid black border
   this paragraph will also be in Arial font due to the first rule which also applies
   but the color will NOT be red */

p#author-info {
    border: 1px solid black;
}

See the Pen CSS selectors – the basics by David Fox (@foxbeefly) on CodePen.

1.1 Group

You can group selectors in a short-hand kind of way:

/* all of your headings will be in red text */

h1, h2, h3, h4, h5, h6 {
    color: red;
}

2. Not so simple

2.1 Chaining

Selectors can be “chained” together to create complex conditions for applying formatting rules:

/* Selects the first <p> element that is placed immediately after <div> elements */

div + p {
    font-style: italic;
}

2.2 Pseudo class selector

Head on over to read about the :nth-child class selector.


As usual, I direct you to the gurus for a comprehensive list: CSS Selectors

By foxbeefly

PHP / MySQL Developer. HTML, CSS and some JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.