CSS Selectors | Everything you need to know

CSS Selectors | Everything you need to know

Hello World! This blog is focused on the different types of CSS selectors and how we can use them to design a better-looking website.

Prerequisite

To get the most out of this article Need to know the following,

  • Basic understanding of HTML.

  • Visual studio code or any IDE of our choice to code along.

What is a selector in CSS?

Selectors are used to select any HTML elements to tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.
or " CSS Selectors are used to "find"(or select) the HTML elements you want to style" There are many varieties of selectors available, each with its unique syntax. This article will discuss the different types of selectors and how they work with examples.

Syntax for CSS selector is :

selector{
    property:value;
}

Types of selectors

  1. Basic selector

They select elements based on element name, id, or class.

  • Universal selector(*): selects all the HTML elements on a page.

  • Type selector: selects an HTML element with the specified tag name.

  • Class selector(.classname): selects a group of HTML elements having the same class name.

  • ID selector(#id): select an HTML element with a unique id.

  • Attribute selector: Selects all elements that have the given attribute or attribute value.

  1. Grouping selector

  • Selector list(,): selects all the matching nodes.
  1. Combinators

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

  • Child combinator(>): selects nodes that are direct children of the first element.

  • General sibling combinator(~): selects siblings.

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

  1. Pseudo

  • Pseudo-classes(:): selection of elements based on state information that is not contained in the document tree.

  • Pseudo-elements(::): represent entities that are not included in HTML.

1. Basic selector

Universal Selector

A universal selector is used to select all the elements on the web page. This means that any style given to the universal selector affects every element on that very page. Represented by asterisk * sign. We normally see this selector in the "reset stylesheet" which removes all browser styles. A universal selector is not used often because it is difficult to add the same style to all elements on the page.

Syntax :

*{
  property: value;
}

Example :

HTML

<h1>This is Universal selector example</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>

CSS

*{
    color: #7f3f99;
    font-family: 'Lucida Sans';
  }

OUTPUT:

universalselector.png

In the above👆 example, the color and font-family will be the same for all the elements.

Type selector

Type selector (is referred to as a tag name selector or element selector) selects the HTML tag/element in the document. It selects all HTML elements based on the given type. It is used to select every instance of the element attached to it on the HTML page.

Syntax:

*{
  property: value;
}

Example:

HMTL

<p>Every paragraph is affected by the style</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>

CSS

p {
  color: #7026a8;
  font-size: 24px;
  font-family: monospace;
  font-weight: 600;
}

OUTPUT:

typeselector.png

In the above👆 example, all paragraph p elements will be having the same color, font-size, font-family, and font-weight.

Class selector

The class selector is probably the most useful and versatile, it selects all elements that have given the class value in their class attribute.

Syntax :

.class{
  property: value;
}

Example :

HTML

  <h1 class="center">The class selector</h1>
  <p class="center">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
  <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p>

CSS

.center {
        text-align: center;
        color: #2626ef;
        font-size: 36px;
        font-family: "Lucida Sans";
        border: 2px solid #524f4f;
      }

OUTPUT:

classselector.png

In the above👆 example, all HTML element with class center, have text-align is center, color is #2626ef, font-size is 36px, font-family is "Lucida Sans" and border is 2px solid #524f4f.

ID selector

The id selector identifies an element based on the id attribute of an HTML document. ID selector is unique and In an HTML document, we can't have more than one element with the same ID.

Note: The ID of an element must be unique on the webpage. Even though HTML allows you to assign the same id value to several elements, you shouldn't ever do it. If you want to assign the same style for many different elements always class should be used. Using ID more than once is violation of HTML Standerd

Syntax :

#idname{
  property: value;
}

Example :

HTML

<table id="users-table">
          <th>Users</th>
          <tr>
            <td>John Doe</td>
          </tr>
          <tr>
            <td>Jane Doe</td>
          </tr>
        </table>
        <table id="staff-table">
          <th>Staff</th>
          <tr>
            <td>Hannah Legend</td>
          </tr>
          <tr>
            <td>Daniel Oaks</td>
          </tr>
</table>

CSS

  /* Type selector */
      table {
        padding: 20px;
      }
      /* ID selectors */
      #users-table {
        background-color: black;
        color: white;
        float: left;
        margin-right: 10px;
      }
      #staff-table {
        border: 1px solid black;
      }

OUTPUT:

idselector.png

In the above👆 example, the CSS rule will be applied to the HTML element with the ID name #users-table and #staff-table only.

What Is the Difference Between CSS Class selectors and ID selectors?

CSS class selector can be repeated but ID selector cannot be repeated and must be unique

Attribute Selector

Selects all elements that have the given attribute or attribute value. The attribute selector is more complex than the rest of the selectors and has several syntaxes that can be applied to our HTML elements based on which condition should be satisfied by them.

Types:

  • Present Attribute Selector

  • Equals Attribute Selector

  • Begins With Attribute Selector (^)

  • Ends With Attribute Selector ($)

  • Attribute Spaced Selector (~)

  • Contains Attribute Selector (*)

  • Hyphen Attribute Selector (|)

Present Attribute Selector

Select elements with the specified attribute.

Syntax :

selector[attribute] {
    property: value;
}

Example :

HTML

<a href="#" target="_blank">Code everyday</a><br />
<a href="#">Code Daily</a><br />
<a href="#" target="_blank">Code Once A Day</a>

CSS

a[target] {
    color: orange;
    font-size: 20px;
}

OUTPUT:

Present Attribute Selector.png

In the above👆 example, the CSS rule will be applied to any <a> element with a "target" attribute. The styles will not apply to all other anchors <a> elements that don't have a target attribute.

Equals Attribute Selector

Equals attribute selectors select elements with a specified attribute and value.
The equals (=) character represents Equals attribute selectors.

Syntax :

selector[attribute="value"] {
   property: value;
}

Example :

HTML

<a href="https://ineuron.ai/" target="_blank">ineuron</a><br />
<a href="https://web.learncodeonline.in/" target="_blank">learncodeonline</a>

CSS

a[href="https://ineuron.ai/"]
  {
    color: #ad7814;
    font-size: 20px;
  }

OUTPUT:

Equals Attribute Selector.png

In the above👆 example, the CSS rule will be applied to every element that has the type attribute with an exact value of the text.

Begins With Attribute Selector (^)

select elements whose attribute value begins with a specific value. No need to specify the whole value when using Begins with selector.
The circumflex accent (^) character represents Begins with selector.

Syntax :

selector[attribute^="value"] {
   property: value;
}

Example :

HTML

<a href="https://ineuron.ai/" target="_blank">ineuron</a><br />
<a href="web.learncodeonline.in" target="_blank">learncodeonline</a>

CSS

a[href^="https://"]
  {
    color: #ad7814;
    font-size: 20px;
  }

OUTPUT:

Begins With Attribute Selector.png

In the above👆 example, the CSS rule will be applied to any <a> element with a href attribute that starts with "https://"

Ends With Attribute Selector ($)

select elements whose attribute value ends with a specific value. No need to specify the whole value when using Ends with a selector.Ends with a selector is the opposite of the begins with selector.
The dollar sign ($) character represents Ends with selector.

Syntax :

selector[attribute$="value"] {
   property: value;
}

Example :

HTML

<a href="https://ineuron.ai/courses" target="_blank">ineuron</a><br />
<a href="https://courses.learncodeonline.in/learn" target="_blank">learncodeonline</a>

CSS

 a[href$="/courses"] 
  {
    color: #93691a;
    font-size: 24px;
  }

OUTPUT:

Ends With Attribute Selector.png

In the above👆 example, the CSS rule will be applied to any <a> element with a ''href'' attribute that ends with "/courses."

Attribute Spaced Selector (~)

Attribute spaced Selector is also called white space attribute selector. It matches any element whose attribute value is a list of space-separated values. By space-separated values, we mean attribute values like class="Coding is fun"
The tilde (~) character represents Contains Attribute selector.

Syntax :

selector[attribute~="value"] {
   property: value;
}

Example :

HTML

<a href="https://ineuron.ai/courses" rel="coding is fun" target="_blank">ineuron</a><br />
<a href="https://courses.learncodeonline.in/learn" target="_blank">learncodeonline</a>

CSS

 a[rel~="coding"] 
  {
    color: #ff0037;
    font-size: 24px;
  }

OUTPUT:

Attribute Spaced Selector.png

In the above👆 example, the CSS styles will be applied to any <a> with a rel attribute with a value of coding.

Contains Attribute Selector (*)

Contains attribute selector select elements whose attribute value contains a specified value.
The asterisk (*) character represents Contains Attribute selector.

Syntax :

selector[attribute*="value"] {
   property: value;
}

Example :

HTML

<a href="https://ineuron.ai/courses" rel="coding is fun" target="_blank">ineuron</a><br />
<a href="https://courses.learncodeonline.in/learn" target="_blank">learncodeonline</a>

CSS

a[href*="courses"] 
  {
    color: #ff0037;
    font-size: 24px;
  }

OUTPUT:

Contains Attribute Selector.png

In the above👆 example, the CSS styles will be applied to any <a> with a href attribute with a value of courses.

Hyphen Attribute Selector (|)

It selects all elements whose attribute has a hyphen-separated list of values. The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text"!
The vertical line (|) character represents Hyphen Attribute Selector

Syntax :

selector[attribute|="value"] {
   property: value;
}

Example :

HTML

<a href="#" lang="en-US">Code Documentation</a>

CSS

 a[lang|="en"] 
  {
    color: #311cba;
    font-size: 24px;
  }

OUTPUT:

Hyphen Attribute Selector.png

In the above👆 example, the CSS styles will be applied to any <a> with a lang attribute with a value of en.

It matches the elements with the lang attribute with the values en en-US en-GB and so on but not US-en, GB-en.

2. Grouping selector

Selects all the HTML elements with the same style. It saves time and helps us write more specific codes. It is used to minimize the code. Commas are used to separate each selector in the grouping. We may need to apply the same style to many HTML components at times.

Selector list

The CSS selector list (,) selects all the matching nodes.

Syntax :

element, element, element { style properties }

Without Grouping

h1 {
  background-color: red;
   color: white;
   font-weight: 700;
   font-size: 28px;
   text-align: center;  
}

h2 {
   background-color: red;
   color: white;
   font-weight: 700;
   font-size: 28px;
   text-align: center;
}

h3 {
   background-color: red;
   color: white;
   font-weight: 700;
   font-size: 28px;
   text-align: center;
}

With grouping

h1, h2, h3 {
   background-color: red;
   color: white;
   font-weight: 700;
   font-size: 28px;
   text-align: center;
}

Example :

HTML

<h1 id="tech">Coding is life</h1>
<p class="future">Coding is fun</p>
<p>Ineuron have Best courses</p>

CSS

#tech,
.future,
p {
    font-size: 20px;
    color: red;
    text-transform: capitalize;
    }

OUTPUT:

Grouping selector.png

In the above👆 example, the CSS styles will be applied to all #tech id's, .future classes, and p elements.

3. Combinators

Combinators help you select items based on their position in the document. CSS selectors rely on the HTML document tree. It's necessary to know the relationship between HTML elements.

Document Tree consists of descendants, parents, children, and sibling elements.

  • A parent element contains other elements.

  • The child element is an element immediately contained by another element.

  • A sibling is an element that shares the same parent with another element.

<div>
   <img src="" alt="">

   <article>
       <h1>coding is FUN</h1>
       <p>Code daily</p>
    </article>

       <aside>
             <h2>Write code daily and</h2>
              <p>Became a software developer </p>
       </aside>

</div>

In the above👆 example,

  • The <div> is the parent.

  • The <img> in line 2, <article> in line 3 and the <aside> element in line 7 are the children of the <div>.

  • The <article> element in line 3 is the parent of the <h1> in line 4 and the <p> element in line 5.

  • The <h1> in line 4 and the <p> element in line 5 are siblings with the same parent <article> element.

  • The <h1> in line 4 and the <p> element in line 5 are the children of the <article> and the grandchildren of the <div> element

  • The <aside> element in line 7 is the parent of the <h2> in line 8 and the <p> element in line 9.

Descendant combinator("")

Represented by "". It matches all elements that are descendants of a specified element. It selects the children, grandchildren, etc when used. To select Descendants, use multiple selectors separated by spaces.

Syntax :

selector1  selector2 {
   property: value;
}

Example :

HTML

<h2>Coding is Fun</h2>
<article>
       <h2>Harsh - The Frontend Web developer</h2>
       <p>I will be working as a full-time frontend web developer by this time next year</p>
<div>
     <h2>Coding is life</h2>
     <p>I prefer using CSS flexbox to Grid</p>
</div>
</article>

In the above example:

  • <h2> element in line 1 is outside the <article> element.

  • <h2> in line 3, <p> in line 4 and <div> elements in line 5 are the children of the <article> element.

  • <h2> in line 6 and <p> element in line 7 are the children of the <div> element in line 5, which makes them the grandchildren of the <article> element.

Remember Descendant selector selects both the children and the grand-children when used.

CSS

article h2 
{
    text-align: center;
    color: orange;
    font-size: 20px;
}

OUTPUT:

Descendant Combinator.png

In the above👆 example, the CSS styles will be applied to all <h2> elements within the <article> element.

Child combinator(>)

Represented by >. It matches an element that is an immediate child of another element. It selects only the child elements. The child combinator selector does not select the grandchildren elements like the Descendant selector. Use the greater-than sign (>) character to represent a child selector. Place the greater than sign (>) between the parent and child element.

Syntax :

Parent-selector > Child-selector {
    property: value;
}

Example :

HTML

<h2>Coding is Fun</h2>
<article>
       <h2>Harsh - The Frontend Web developer</h2>
       <h2>Kunal - The FullStack Web developer</h2>
       <p>I will be working as a full-time frontend web developer by this time next year</p>
<div>
     <h2>Coding is life</h2>
     <p>I prefer using CSS flexbox to Grid</p>
</div>
</article>

CSS

article > h2 
  {
    text-align: center;
    color: orange;
    font-size: 20px;
  }

OUTPUT:

Child combinator.png

In the above👆 example, the CSS styles will be applied to all <h2> elements which are child to <article> element. For the rest of the <h2> elements, CSS styles will not be applied.

The difference between a Descendant Combinator Selector and Child Combinator Selector?
The descendant combinator selects all the children or grandchildren of a given element. The child combinator selector ( > ) targets an element that is a child of its parent. It does not target beyond the children.

General sibling combinator(~)

Represented by ~. Select the elements that follow and share the same parent. It is not necessary that the second element immediately follows the first element.

Syntax :

first-sibling-selector ~ second-sibling-selector {
   property: value;
}

Example :

HTML

 <span>This is not red.</span>
<p>Here is a paragraph.</p>
<code>Here is some code.</code>
<span>And here is a red span!</span>
<span>And this is a red span!</span>
<code>More code…</code>
<div>How are you?</div>
<p>Whatever it may be, keep smiling.</p>
<h1>Dream big</h1>
<span>And yet again this is a red span!</span>

CSS

p ~ span
  {
     color: red;
  }

OUTPUT:

General sibling.png

In the above👆 example, the CSS styles will be applied to all <span> elements that come after the <p> element.

Adjacent sibling combinator(+)

Represented by + symbol. Matches with the second element only if it immediately follows the first element. Sibling elements must have the same parents.

Syntax :

first-sibling-selector + second-sibling-selector {
    property: value;
}

Example :

HTML

<h1>Coding is fun</h1>
<p>Ineuron has best cources</p>
<p>Coding is life</p>

CSS

h1 + p{
    color: #0ea2c6;
}

OUTPUT:

Adjecent sibling.png

In the above👆 example, the CSS styles will be applied to first <p> element only because second one doesn't appear immediately after <h1> element.

4. Pseudo

Pseudo-Class

Pseudo class is a keyword, added to a selector which specifies special state of selected element(s). It is added to selector to add special effect to the existing element based on their state. pseudo-classes are always preceded by a :.
Some of the most common CSS pseudo-classes are: :active, :hover, :focus, :disabled, :checked, :first-child, :nth-child, :first-of-type.

Syntax :

element : pseudo-class { 
style properties 
}

Example :

HTML

<h1>Coding is fun</h1>
<p>Ineuron has best cources</p>
<button class="btn ineuron">Buy Course</button>
<p>Coding is life</p>

CSS

.btn{
    background-color: transparent;
    border: 2px solid #1f1f1f;
    border-radius: .5em;
    padding: 1em 2em;
}

.ineuron{
    transition: color 300ms ease-in-out;
    cursor: grab;
}

.ineuron:hover{
  box-shadow: 0 0 40px 40px #1f1f1f inset;
  color: #fff;
}

OUTPUT:

pseudoclass.png

In the above👆 example, the CSS styles will be applied to :hover keyword. When we hover on the button the color of the text and background of the button changes.

Pseudo-Elements

Pseudo-element behaves similar way as pseudo-class but they act as a whole new HTML added into the markup. Pseudo-elements is like virtual element that we can consider as regular HTML element and they don't exist in DOM. So we actually create them in CSS. pseudo-classes are always preceded by a ::.
Some of the most common CSS pseudo-elements are: ::after, ::before, ::marker, ::placeholder, ::first-letter.

Syntax :

element :: pseudo-element{ 
style properties 
}

Example :

HTML

<h1>Coding is fun</h1>
<p>Ineuron has best cources</p>
<button class="btn ineuron">Buy Course</button>
<p>Coding is life</p>

CSS

p::before{
  content: "_";
}

OUTPUT:

pseudoelement.png

In the above👆 example, the CSS styles will be applied to <p> tag. We will add underscore(_) beginning of every <p> tag.

Did you find this article valuable?

Support K Subramanyeshwara by becoming a sponsor. Any amount is appreciated!