Affiliate link

CSS - Selectors

CSS selectors are used to select HTML elements and apply the CSS styles.

CSS selectors

Ways to define CSS selectors:

  • Select all HTML with universal selector *
  • Select HTML elements by element tag
  • Select HTML elements by id, or class
  • Select HTML elements by their state
  • Select HTML elements by element's attributes
  • Combination of selectors

Select HTML elements by element tag

To define the CSS properties for element/tag, you can use the element/tag name.
Example, h1, span, p.

<html>
    <head>
        <style>
            h1 {
                color: #0070f3; 
            }
        </style>
    </head>
    <body>
        <h1>Learn CSS selectors</h1>
    </body>
</html>

Code Result

Select HTML elements by id, or class

To define the CSS properties for element by id, you can use the id name with #.
Example, #learnSelector.
To define the CSS properties for element by class, you can use the class name with ..
Example, .selectorStyle.

<html>
    <head>
        <style>
            h2 {
                color: #0070f3;
            }
            #learnSelector {
                color: red;
            }
            .selectorStyle {
                color: green;
            }
        </style>
    </head>
    <body>
        <h2>Learn CSS selectors</h2>
        <h2 id="learnSelector">Learn CSS selectors</h2>
        <h2 class="selectorStyle">Learn CSS selectors</h2>
    </body>
</html>

Code Result

Affiliate link

Select HTML elements by their state

Select HTML elements by their state

<html>
    <head>
        <style>
            .learnSelector:hover {
                width: auto;
                color: #0070f3;
            }
        </style>
    </head>
    <body>
        <h2 class="learnSelector">Learn CSS selectors (Mouse over to me to change color)</h2>
    </body>
</html>

Code Result

Style Precedence

CSS style precedence are cascaded by specificity and inheritance.

Selector specificity

Higher specificity will override lower specificity.

SelectorExampleSpecificity
Universal selector
Combinator
*
+
1
Element
Pseudo-element
div
::first-child
2
Element Class
Pseudo-class
Attribute
.learnSelector
:hover
[type="radio"]
3
Element ID#learnSelector4
Inline style attributestyle="color: blue;"5
Affiliate link
Affiliate link
Advertisment
Fiverr
Get Surfshark VPN