CSS - tutorial - 07 - CSS selectors

Revision:


Content

CSS selectors are patterns used to select the element(s) you want to style. Structure of a selector Simple selectors Compound selectors Combinators Attribute selectors Grouping selector Pseudo-classes and pseudo-elements


CSS selectors are patterns used to select the element(s) you want to style.

top

CSS selectors define the pattern to select elements to which a set of CSS rules apply.

They are used in the CSS file or inside the "style" tag while declaring the CSS.

CSS selectors play an essential role in applying the style to multiple elements at once.

CSS selectors can be grouped into the following categories based on the type of elements they can select.

Basic selectors:

Universal selector (*) : Selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces. It can be used on all elements of a website and matches elements of any type. CSS styles applied to a universal selector affects each and every element(including <html> and <body>) on the page. The asterik is optional with simple selectors. The * selector can also select all elements inside another element, e.g. to select all the elements in a <div> element

Syntax: * ns|* *|* ; * {style properties}; * { property : value}

example: "*" will match all the elements of the document

Type selector : selects all elements that have the given node name.

Syntax: elementname

example: "input" will match any <input> element.

Class selector : selects all elements that have the given "class" attribute.

Syntax: .classname

example: ".index" will match any element that has class="index".

ID selector : selects an element based on the value of its "id" attribute. There should be only one element with a given ID in a document.

Syntax: #idname

example: "#toc" will match the element that has id="toc".

Attribute selector : selects all elements that have the given attribute.

Syntax: [attr], [attr=value], [attr~=value], [attr|=value], [attr^=value], [attr$=value], [attr*=value]

example: "[autoplay]" will match all elements that have the "autoplay" attribute set (to any value).

Grouping selectors

Selector list : the "," selector is a grouping method that selects all the matching nodes.

Syntax: A, B

example: "div", "span" will match both <span> and <div> elements.

Combinators

Descendant combinator : the " " (space) combinator selects nodes that are descendants of the first element.

Syntax: A B

example: "div" "span" will match all <span> elements that are inside a <div> element.

Child combinator : the ">" combinator selects nodes that are direct children of the first element.

Syntax: A > B

example: "ul" > "li" will match all <li> elements that are nested directly inside a <ul> element.

General sibling combinator : The "~" combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.

Syntax: A ~ B

example: "p" ~ "span" will match all <span> elements that follow a <p>, immediately or not.

Adjacent sibling combinator : the "+" combinator matches the second element only if it immediately follows the first element.

Syntax: A + B

example: "h2" + "p" will match the first <p> element that immediately follows an h2 element.

Column combinator : the "||" combinator selects nodes which belong to a column.

Syntax: A || B

example: "col" || "td" will match all <td> elements that belong to the scope of the <col>.

Pseudo-classes and pseudo-elements

Pseudo-classes : the ":" pseudo allow the selection of elements based on state information that is not contained in the document tree.

example: "a:visited" will match all <a> elements that have been visited by the user.

Pseudo-elements : The "::" pseudo represent entities that are not included in HTML.

example: "p::first-line" will match the first line of all <p> elements.


Structure of a selector

top

The term "selector" can refer to one of the following:

Simple selector

A selector with a single component, such as a single id selector or type selector, that's not used in combination with or contains any other selector component or combinator.
A given element is said to match a simple selector when that simple selector accurately describes the element. All basic selectors, attributes, and single pseudo-classes and pseudo-elements are simple selectors.

Compound selector

A sequence of simple selectors that are not separated by a combinator.
A compound selector represents a set of simultaneous conditions on a single element. A given element is said to match a compound selector when the element matches all the simple selectors in the compound selector.
In a compound selector, the type selector or a universal selector in a compound selector must come first in the sequence of selectors. Only one type selector or universal selector is allowed in the sequence.
Since whitespace represents the descendant combinator, no whitespace is allowed between the simple selectors in a compound selector.

Example: a#selected {...}

Complex selector

A sequence of one or more simple and/or compound selectors that are separated by combinators.
A complex selector represents a set of simultaneous conditions on a set of elements. These conditions apply in the context of relationships described by the combinators.
A given element is said to match a complex selector when the element matches compound selectors and the combinators between the compound selectors.

Example: a#selected > .icon {...}, .box h2 + p {...}, a .icon {...}

Relative selector

A selector representing an element relative to one or more anchor elements preceded by a combinator.
Relative selectors that don't begin with an explicit combinator have an implied descendant combinator.

Examples: + div#topic > #reference {...}, > .icon {...}, dt:has(+ img) ~ dd {...}

Selector list

A comma-separated list of simple, compound, or complex selectors.
If the constituent selector type of a selector list is important but unspecified, it is called a complex selector list.
A given element is said to match a selector list when the element matches any (at least one) of the selectors in that selector list.

Example: #main, article.heading {...}


Simple selectors

top

CSS "element" selector : selects HTML elements based on the element name.

Syntax: element{css declarations;}

examples

My name is Seppe.

I live in Leuven.

My best friend is Edgard.

code:
                    <style>
                        p.tel {background-color: lightcyan;}
                    </style>
                    <div>
                        <div class="introduc">
                            <p class="spec tel" id="firstN">My name is Seppe.</p>
                            <p class="spec tel" id="homeT">I live in Leuven.</p>
                        </div>
                        <p class="spec tel">My best friend is Edgard.</p>
                    </div>
                

CSS "id" selector: styles the element with the specified id.

Syntax: #id {css declarations;}

examples

My name is Nicolas.

I live in Antwerp.

My best friend is Jasper.

code:
                    <style>
                        #firstname {background-color: lightcyan;}
                    </style>
                    <div class="introd">
                        <p class="spec" id="firstname">My name is Nicolas.</p>
                        <p class="spec" id="hometown">I live in Antwerp.</p>
                    </div>
                    <p class="spec">My best friend is Jasper.</p>
                

CSS "class" selector : selects elements with a specific class attribute

To select elements with a specific class, write a period (.) character, followed by the name of the class.
You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.) character, followed by the name of the class.
HTML elements can also refer to more than one class.

Syntax: .class {css declarations;}

examples

My name is Eric.

I live in Brussels.

My best friend is Andre.

My best friend is Andre.

code:
                    <style>
                        .intro {background-color: lightcyan;}
                    </style>
                    <div class="intro">
                        <p class="spec">My name is Eric.</p>
                        <p class="spec">I live in Brussels.</p>
                    </div>
                    <p  class="spec">My best friend is Andre.</p>
                    <p  class="spec intro">My best friend is Andre.</p>                                            
                

This heading will not be affected

This paragraph will be red and center-aligned.

This paragraph will be red, center-aligned, and in a large font-size.

code:
                    <style>
                        p.center {text-align: center; color: red;}
                        p.large {font-size: 300%;}
                    </style>
                    <h3 class="center">This heading will not be affected</h3>
                    <p class="center">This paragraph will be red and center-aligned.</p>
                    <p class="center large">This paragraph will be red, center-aligned, and in a large font-size.</p> 
                

CSS "universal" "(*)" selector : selects all elements.

The * selector can also select all elements inside another element.

Syntax: * {css declarations;}

examples

My name is Nicole.

I live in Hasselt.

My best friend is Wendy.

code:
                    <style>
                        .introdu * {background-color: lightcyan;}
                    </style>
                    <div class="introdu">
                        <p class="spec" id="first">My name is Nicole.</p>
                        <p class="spec" id="home">I live in Hasselt.</p>
                    </div>
                    <p class="spec">My best friend is Wendy.</p>
                

Some syntax examples

        * {margin: 1.5vw; color:green;}
        * [lang=en]{ color: blue;}
        *.warning{ color: red;}
        *#maincontent{border: 1px solid blue; }
    

Compound selectors

top

The ".class1.class2" selector : selects all elements with both class1 and class2 set within its class attribute.

The element containing both of the classes will be styled only. All the other elements containing either one or zero of the two classes will not be styled.

Note: in the CSS selector, there is no space between the class names.

examples
Hello there.
Welcome to this file.
Like this file?
code:
                    <style>
                        .para.second {font-size: larger; margin-bottom: 35px; margin-top: 35px;background-color: lightgreen; color: red;}
                     </style>  
                     <div>
                         <a style="margin-left:3vw;" class="para">Hello there.</a><br>
                         <a style="margin-left:3vw;" class="para second">Welcome to this file.</a><br>
                         <a style="margin-left:3vw;" class="second">Like this file?</a>
                     </div> 
                

The "element.class" selector is used to select the specified element with the specified class.

Syntax: element.class {css declarations;}

examples

My name is Elodie.

I live in Brugge.

My best friend is Astrid.
code:
                    <style>
                        p.tele {background-color: lightblue;}
                    </style>
                    <div>
                        <div class="introduction">
                            <p class="spec tele" id="firstN">My name is Elodie.</p>
                            <p class="spec tele" id="homeT">I live in Brugge.</p>
                        </div>
                        <div class="spec tele">My best friend is Astrid.</div>
                    </div>
                

Combinators

top

CSS combinators can be used to combine two or more simple selectors.

Syntax:

" space " : descendant selector: matches all elements that are descendants of a specified element..

" > ": child selector: selects all elements that are the children of a specified element; find all elements that are direct children of a specific element.

" + ": adjacent sibling selector: is used to select an element that is directly after another specific element;find all elements only if it immediately follows the first element.

" ~ ": general sibling selector: selects all elements that are next siblings of a specified element; find any elements that are siblings of an element.

example:

        div p {background-color: green;}
        div > p{background-color: black;}
        .parent-container > p {color:darkgreen;}
        div + p{background-color: blue;}
        p + p{background-color: red}
        h2 + p{ font-size: 1em; color: orange;}
        .panda ~ .panda{background-color: lightgreen;}
        article ~ h2{ font-weighjt: bold;}
        *.successs{ background-color: green:}
        .navigation-menu > ul > li > a{font-weight: bold;}
    

Descendant selector (" "): matches all elements that are descendants of a specified element

Descendant selector matches all elements that are descendants of a specified element.

Example : div p {background-color: yellow;}
explanation: the example selects all <p> elements inside <div> elements

The ".class1 .class2" selector selects all elements with class2 that is a descendant of an element with class1.

Note: in this CSS selector, there is space between the class names.

examples
this paragraph will not be styled
code:
                    <style>
                        .chapter .para {float: left;font-size: 150%; background-color: lightcyan;}
                    </style>  
                    <div>
                        <div style="margin-left:3vw;" class="chapter">
                        <a style="margin-left:3vw;">this is the title section of this example</a><br>
                        <a style="margin-left:3vw;" class="para">this paragraph will be styled.</a><br><br>
                        <a style="margin-left:3vw;" class="para-2">this paragraph will not be styled.</a><br>
                        </div>
                        <a style="margin-left:6vw;" class="para">this paragraph will not be styled</a>
                    

The "element element" selector is used to select elements inside elements.

Syntax: element element {css declarations;}

examples

Welcome to my homepage

My name is Albert.

I live in Diest.

My best friend is Rene.

code:
                    <style>
                        .even p {background-color: burlywood;}
                    </style>
                    <div>
                        <div class="even">
                            <h4>Welcome to my homepage</h4>
                            <p class="spec one" id="firstN">My name is Albert.</p>
                            <p class="spec one" id="homeT">I live in Diest.</p>
                        </div>
                        <p class="spec one">My best friend is Rene.</p>
                    </div>
                

Child selector (>) : selects all elements that are the children of a specified element.

Child selector (>) selects all elements that are the children of a specified element.

Example : div > p {background-color: yellow;}
explanation: the example selects all <p> elements that are children of a <div> element.

The element>element selector is used to select elements with a specific parent. Elements that are not directly a child of the specified parent, are not selected.

Syntax: element > element {css declarations;}

examples
Welcome to my homepage

My name is Erwin.

I live in Mechelen.

I will not be styled.

code:
                    <style>
                        .odd > p {background-color: orange;}
                    </style>
                    <div>
                        <div class="odd">
                            <h5 class="spec">Welcome to my homepage</h5>
                            <p class="spec one" id="firstN">My name is Erwin.</p>
                            <p class="spec one" id="homeT">I live in Mechelen.</p>
                        </div>
                        <div>
                            <span><p class="spec one">I will not be styled.</p></span>
                        </div>
                    </div>
                

General sibling selector (~) : selects all elements that are next siblings of a specified element.

General sibling selector (~) selects all elements that are siblings of a specified element

Example : div ~ p {background-color: yellow;}
explanation: the example selects all <p> elements that are siblings of <div> elements

The element1 ~ element2 selector matches occurrences of element2 that are preceded by element1. Both elements must have the same parent, but element2 does not have to be immediately preceded by element1.

Syntax: element ~ element {css declarations;}

examples
A div element.
  • Coffee
  • Tea
  • Milk

The first paragraph.

  • Coffee
  • Tea
  • Milk

Another list

  • Coffee
  • Tea
  • Milk
code:
                    <style>
                        p ~ ul {background: #ff0000;}
                    </style>
                    <div>
                        <div style="margin-left:3vw;">A div element.</div>
                            <ul>
                            <li>Coffee</li>
                            <li>Tea</li>
                            <li>Milk</li>
                            </ul>
            
                            <p class="spec">The first paragraph.</p>
                            <ul>
                            <li>Coffee</li>
                            <li>Tea</li>
                            <li>Milk</li>
                            </ul>
            
                            <h4>Another list</h4>
                            <ul>
                            <li>Coffee</li>
                            <li>Tea</li>
                            <li>Milk</li>
                            </ul>
                    </div>
                

Adjacent sibling selector (+) : selects an element that is directly after another specific element.

Adjacent sibling selector (+) is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".

Example : div + p {background-color: yellow;}
explanation: the example selects the first <p> element that are placed immediately after <div> elements

The element + element selector is used to select an element that is directly after another specific element.

Syntax: element + element {css declarations;}

examples

Welcome to my homepage

My name is Pieter.

I live in Ghent.

My best friend is Edward.

I will not be styled.

code:
                    <style>
                        .two + p {background-color: pink;}
                    </style>
                    <div>
                        <div class="two">
                            <h4>Welcome to my homepage</h4>
                            <p class="spec one" id="firstN">My name is Pieter.</p>
                            <p class="spec one" id="homeT">I live in Ghent.</p>
                        </div>
                        <p>My best friend is Edward.</p>
                        <p>I will not be styled.</p>
                    </div>
                

Attribute selectors

top

Attribute selectors can be used on certain elements having similar attributes but different class names. It is possible to style HTML elements that have specific attributes or attribute values.

Syntax:

[attr] : is used to select elements with a specified attribute.

[attr=value] : is used to select elements with a specified attribute and value.

[attr~=value] : is used to select elements with an attribute value containing a specified word.

[attr|=value] : is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-).

[attr^=value] : is used to select elements with the specified attribute, whose value starts with the specified value.

[attr$=value] : is used to select elements whose attribute value ends with a specified value.

[attr*=value] : is used to select elements whose attribute value contains a specified value. The value does not have to be a whole word!

example:

        button[id]{color:green; }
        button[class="btnStyle"]{ color: white;}
        button[class^="btn"]{ color: orange;}
        button[class$="Style"]{ color: purple;}
        button[class*="nSty"]{ color: yellow;}
        [class*="component_"]{ border: 2px solid blue;}
        input[type="checkbox"]{background-color: orange;}
        a[href="http://www.google.com"]{background-color: yellow;}
        img[alt~="art"]{border: 3px solid lightgreen;}
        li[data-years|="1900"]{ color: red;}
    

CSS "[attribute]" selector : is used to select elements with the specified attribute.

Syntax: [attribute] {css declarations;}

examples

The links with a target attribute gets a yellow background:

lwitters.com disney.com wikipedia.org
code:
                    <style>
                        a[target] { background-color: yellow;}
                    </style>
                    <div> 
                        <p>The links with a target attribute gets a yellow background:</p>
                        <a style="margin-left: 3vw;" href="https://www.lwitters.com">lwitters.com</a>
                        <a href="http://www.disney.com" target="_blank">disney.com</a>
                        <a href="http:///www.wikipedia.org" target="_top">wikipedia.org</a>
                    </div>
                

CSS "[attribute=value]" selector : is used to select elements with the specified attribute and value.

Syntax: [attribute = value] {css declarations;}

examples

The link with target="_blank" gets a lightgreen background:

w3schools.com disney.com wikipedia.org
code:
                    <style>
                        .three[target=_blank] {background-color: lightgreen;}
                    </style>
                    <div>
                        <p>The link with target="_blank" gets a lightgreen background:</p>
                        <a style="margin-left: 3vw;" class="three" href="https://www.w3schools.com">w3schools.com
                        <a class="three" href="http://www.disney.com" target="_blank">disney.com</a>
                        <a class="three" href="http://www.wikipedia.org" target="_top">wikipedia.org</a>
                    </div>
                

CSS "[attribute~=value]" selector is used to select elements with an attribute value containing a specified word.

Syntax: [attribute ~= value] {css declarations;}

examples

The image with the title attribute containing the word "pink" gets a yellow border.

code:
                    <style>
                        [title~=pink] {border: 5px solid yellow;}
                    </style>
                    <div>
                        <p>The image with the title attribute containing the word "pink" gets a yellow border.</p>
                        <img src="../pics/img_orange_flowers.jpg" title="orange flower" width="150" height="113">
                        <img src="../pics/img_pink_flowers.jpg" title=" pink flowers" width="150" height="120">
                        <img src="../pics/img_white_flower.jpg" title="white flowers" width="150" height="120">
            
                    </div>
                

CSS "[attribute|=value]" selector is used to select elements with the specified attribute starting with the specified value.

The value has to be a whole word, either alone, like lang="en", or followed by a hyphen( - ), like lang="en-us".

Syntax: [attribute |= value ] {css declarations;}

examples

Welcome

Hello world!
Are you learning CSS?
And maybe also HTML?
code:
                    <style>
                        [class|=top] {background: lightblue;}
                    </style>
                    <div>
                        <h3 class="top">Welcome</h3>
                        <a style="margin-left:2vw;" class="top-text">Hello world!</a><br>
                        <a style="margin-left:2vw;" class="topcontent">Are you learning CSS?</a><br>
                        <a style="margin-left:2vw;" class="top-content">And maybe also HTML?</a>
                    </div>  
                

CSS "[attribute^=value]" selector matches every element whose attribute value begins with a specified value.

Syntax: [attribute ^= value ] {css declarations;}

examples
The first div element.
The second div element.
The third div element.
The fourth div element.

This is a paragraph.

This is a paragraph.

code:
                    <style>
                        [class^="test"] {background: #ffff00;}
                    </style>
                    <div>
                        <div class="first_test" style="margin-left: 2vw;">The first div element.</div>
                        <div class="second" style="margin-left: 2vw;">The second div element.</div>
                        <div class="test" style="margin-left: 2vw;">The third div element.</div>
                        <div class="test_ex" style="margin-left: 2vw;">The fourth div element.</div>
                        <p class="test">This is a paragraph.</p>
                        <p class="test_ex">This is a paragraph.</p>
                    </div>
                

CSS "[attribute$=value] selector" matches every element whose attribute value ends with a specified value.

Syntax: [attribute $= value ] {css declarations;}

examples
The first div element.
The second div element.
The third div element.

This is some text in a paragraph.

code:
                    <style>
                        [class$="trial"] {background: lightcyan;}
                    </style>
                    <div>
                        <div class="first_trial" style="margin-left: 2vw;"">The first div element.</div>
                        <div class="second" style="margin-left: 2vw;"">The second div element.</div>
                        <div class="trial" style="margin-left: 2vw;"">The third div element.</div>
                        <p class="trial">This is some text in a paragraph.</p>
                    </div>  
                

CSS "[attribute*=value] selector" matches every element whose attribute value contains a specified value.

Syntax: [attribute *= value] {css declarations;}

examples
The first div element.
The second div element.
The third div element.

This is some text in a paragraph.

code:
                    <style>
                        [class*="tryout"] {background: skyblue;}
                    </style>
                    <div>
                        <div class="first_tryout" style="margin-left: 2vw;">The first div element.</div>
                        <div class="second" style="margin-left: 2vw;">The second div element.</div>
                        <div class="tryout" style="margin-left: 2vw;">The third div element.</div>
                        <p class="tryout">This is some text in a paragraph.</p>
                    </div>
                

Grouping selector

top

CSS grouping selector ( , ) : used to select multiple elements and style them together

To style several elements with the same style, separate each element name with a comma.

Syntax: element, element {css declarations;}

examples

Welcome to my homepage

My name is Stefan.

I live in Liege.

My best friend is Sophie.
code:
                    <style>
                        h4, p.telep {background-color: burlywood;}
                    </style>
                    <div>
                        <div class="introduction">
                            <h4>Welcome to my homepage</h4>
                            <p class="telep" id="firstN">My name is Stefan.</p>
                            <p class="telep" id="homeT">I live in Liege.</p>
                        </div>
                        <div class="telep">My best friend is Sophie.</div>
                    </div>
                

Pseudo-classes and pseudo-elements

top

See the respective tutorials on these selectors.