Important CSS Selectors, You Should Know!

Important CSS Selectors, You Should Know!

What is a selector & Why should you care?

  • A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.
  • The main theme of CSS is for applying styles for web elements to make a web page look good and even more readable.

    Let’s dive into the topic!

List of the CSS Selectors

The following is a list of the most common and well-supported CSS selectors.

  • Universal Selectors
  • Element Type Selectors
  • Class selectors
  • Id Selectors
  • Attribute Selector
  • Combinators
  • Pseudo Selectors

1. Universal Selectors

  • An asterisk * is used to denote a CSS universal selector.
  • It will select all the elements on the web page and it will apply styles to all of them.

For example, if we wanted every element to have a solid 2px wide border, we would use the following CSS rule:

* { border: 2px solid rebeccapurple;}

Result:-

Universal selector.png

2. Element Type Selectors

Selecting an element in CSS can be as simple as using the tag name. This is called the type selector, and all HTML tags are valid selectors.

For example, in the below code we selected p so it will affect all p elements in a web page.

HTML

<body>
  <h1>This Is A Test Page</h1>
  <p>test1</p>
  <br>
  <p>test2</p>
  <br>
  <p>test3</p>
  <br>
  <p>test4</p>
</body>

CSS

p{
    background-color: yellow;  
}

Result:-

Element Type.png

3. Class Selectors

  • A dot( . ) is used to denote a class selector and it will proceed with a string of characters that the developer defines.
  • It is almost like an Id selector but the only difference is we can use class selectors for multiple elements on a page which will share the same CSS styles.

For example, if we wanted all elements with a class of "highlight" to have a different background color, we would use the following CSS rule:

HTML

<body>
  <h1>Class Selector </h1>
  <p>Lorem ipsum, dolor sit amet <span class="test">consectetur adipisicing elit.</span> Omnis officiis, natus quasi eum earum perspiciatis inventore aspernatur officia quod minus fugit quidem at molestias ut. Quas modi voluptate ea tenetur.</p>
  <br>
  <li class="test">text1</li>
  <li>text2</li>
  <li class="test">text3</li>
  <li>text4</li>
</body>

CSS

.test{
    background-color: rgb(183, 216, 75);  
}

Result:-

Class Selector.png

4. Id Selectors

  • A hash(#) is used to denote an Id selector and it will proceed with a string of characters that the developer defines. The id should be unique for the entire web page which means you are not allowed to assign an id selector for multiple elements.

For example, if we wanted the element with an id of "test", we would use the following CSS rule:

HTML

<body>
  <h1>id Selector </h1>
  <p>Lorem ipsum, dolor sit amet <span class="test">consectetur adipisicing elit.</span> Omnis officiis, natus quasi eum earum perspiciatis inventore aspernatur officia quod minus fugit quidem at molestias ut. Quas modi voluptate ea tenetur.</p>
  <br>
  <ul id="test">
  <li >text1</li>
  <li>text2</li>
  <li >text3</li>
  <li>text4</li>
</ul>
</body>

CSS

#test{
    border: 2px solid brown;  
}

Result:-

id selector.png

5. Attribute Selector

  • Attribute selectors are used to select an element with a specific attribute. For example, in the below code it will select all anchor tags that have a target attribute.

For example, Where this HTML line has a rel attribute with the value of "test".we would use the following CSS rule:

HTML

<body>
  <h1>id Selector </h1>
  <a href="demotext.com" rel="test1">Demo Text</a>
  <br>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. A, atque.</p>
  <br>
  <a href="demotext.com" rel="test">Demo Text2</a>
</body>

CSS

a[rel="test"]{
    background-color: yellow;  
    border: 2px solid rgb(28, 28, 20);
    border-radius: 20px;
}

Result:-

Attribute Selector.png

Basic SelectorAttribute Selector
Select by ID#test[id=test]
Select by Class.test[class~="test"]

6. Combinators

CSS combinators are explaining the relationship between two selectors. CSS selectors are the patterns used to select the elements for style purposes. A CSS selector can be a simple selector or a complex selector consisting of more than one selector connected using combinators.

There are four types of combinators available in CSS which are discussed below:

  • General Sibling selector (~)
  • Adjacent Sibling selector (+)
  • Child selector (>)
  • Descendant selector (space)
NameCombinatorExampleDescription
Descendant" " (space)nav aAll anchor tags inside of a nav element
Child>nav > ul > liFirst list items inside a navigation list, ignoring any items after the first level
Sibling~p ~ pAll paragraphs (after the first) that share the same parent element
Adjacent Sibling+h2 + pAll paragraphs that immediately follow an <h2> tag on the same hierarchy

For example, if we wanted all elements to apply the Combinator property, we would use the following CSS rule:

HTML

<body>
  <h1>Combinators</h1>
  <nav>
  <ul>
  <li><a href="">Home</a></li>
  <li>
  <a href="">Combinators</a>
  <ul>
  <li>" " (space)</li>
  <li>&gt;</li>
  <li>~</li>
  <li>+</li>
  </ul>
  </li>
  </ul>
  </nav>
  <main>
  <h2>List of Combinators</h2>
  <p>There are a few other combinators to make
 this...</p>
  <ul>
  <li>
  " " (space)
  <ul>
  <li>nav li</li>
  <li>nav a</li>
  </ul>
  </li>
  <li>></li>
  <li>~</li>
  <li>+</li>
  </ul>
  <p>By combining selectors together we can
 select...</p>
  </main>
 </body>

CSS

nav a {
    display: block;
    margin: 0 1rem;
   }
   nav > ul > li {
    border: solid 1px gray;
    display: inline-block;
    list-style-type: none;
    vertical-align: top;
   }
   p ~ p {
    color: purple;
    font-weight: bold;
   }
   h2 + p {
    background-color: #ffff00;
   }

Result:-

CSS Combinator.png

7. Pseudo Selectors

There are two types of Pseudo Selectors

i. Pseudo Classes ii. Pseudo Elements

i. Pseudo Classes

  • A Pseudo class in CSS is used to define the special state of an element. It can be combined with a CSS selector to add an effect to existing elements based on their states.
  • For Example, changing the style of an element when the user hovers over it, or when a link is visited. All of these can be done using Pseudo Classes in CSS.
selector:pseudo-class {
  property:value;
}

This selector is therefore very useful to apply styles based on element states.

div:hover {
  background-color: brown;
}

For example, background color can change when a user hovers over an element.

/* unvisited link */
a:link {
  color: #2200ff;
}

/* visited link */
a:visited {
  color: #65068b;
}

unvisited link Or if a link was already clicked before.

input[type=radio]:checked {
  border: 1px solid purple;
}

This pseudo-class will only target a user interface element that has been checked.

Note that pseudo-class names are not case-sensitive.

HTML

<body>
    <h1>Pseudo Classes</h1>
    <table>
      <thead>
        <th>Name</th>
        <th>Email</th>
        <th>Zip Code</th>
      </thead>
      <tbody>
        <tr>
          <td>Demo1</td>
          <td>Demo1@email.com</td>
          <td>15978</td>
        </tr>
        <tr>
          <td>Demo2</td>
          <td>demo2@email.com</td>
          <td>11458</td>
        </tr>
        <tr>
          <td>Demo3</td>
          <td>demo3@email.com</td>
          <td>68978</td>
        </tr>
      </tbody>
    </table>
    <form>
      <label>
        Name:
        <input type="text" maxlength="20" required />
      </label>
      <label>
        Email
        <input type="email" maxlength="100" required />
      </label>
      <label>
        Zip Code:
        <input type="number" max="99999" />
      </label>
      <button type="submit">Submit</button>
    </form>
  </body>

CSS


   tbody tr:nth-last-of-type(odd) {
    background: rgb(140, 112, 144);
   }
   th, td {
    padding: .5rem 1rem;
    text-align: left;
   }

   form > *:not(button) {
    border-radius: 4px;
    box-sizing: border-box;
    display: block;
   }

   input:hover, input:active {
    border-color: rgb(140, 112, 144);
   }
   input:invalid {
    border-left: solid 4px red;
   }

   button:hover, button:active {
    outline: dotted 1px rgb(30, 30, 33);
    outline-offset: 2px;
   }

Result:-

pseudo Classes.png

There are many more useful pseudo-classes.You can check out pseudo-classes with examples here.

ii. Pseudo Elements

A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected elements. For Example, Styling the first letter or line of an element, Insert content before or after the content of an element. All of these can be done using Pseudo Elements in CSS.

selector::pseudo-element {
  property:value;
}
SelectorExampleExample description
::afterp::afterInsert something after the content of each <p> element
::beforep::beforeInsert something before the content of each <p> element
::first-letterp::first-letterSelects the first letter of each <p> element
::first-linep::first-lineSelects the first line of each <p> element
::marker::markerSelects the markers of list items
::selectionp::selectionSelects the portion of an element that is selected by a user

For example::first-line can be used to style the first line of every <p>.

/* The first line of every <p> element. */
p::first-line {
  color: Red;
}

HTML

  <body>
    <h1>Pseudo Elements</h1>
    <p>Lorem ipsum dolor sit amet, consectetur Lorem ipsum 
      dolor sit amet consectetur adipisicing <br> elit. Atque maiores numquam, ipsa fuga debitis nam. Voluptate distinctio quisquam obcaecati maiores lorem300.
   </p>
    <p>Cras id blandit risus. Nunc dictum, elit Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure corporis praesentium ducimus, expedita quos quasi dolorum earum adipisci. Adipisci placeat mollitia sequi necessitatibus praesentium unde id ullam maiores eligendi est, earum perspiciatis eveniet excepturi quisquam odio possimus ad corporis incidunt exercitationem eaque delectus voluptas eum consequuntur. Dolores, sed labore non tempore deleniti voluptatem velit eius rerum fugit ea laborum illo dolorum, itaque vitae? Amet adipisci animi sequi eaque expedita corrupti odit, doloribus ducimus! Animi, hic commodi impedit harum delectus officia omnis aut minima pariatur nobis dolor? Itaque repellat autem numquam.
   </p>
    <p>Quisque euismod tempus erat, sit amet
   pharetra...</p>
   </body>

CSS

p::first-letter {
    color: RGB(70, 4, 4);
    font-size: 3rem;
    line-height: 0;
    display: block;
    float: left;
    margin-top: .125rem;
    margin-right: .5rem;
   }
   p::first-line {
    color: rgb(76, 5, 5);
   }

Result:-

element.png

Did you find this article valuable?

Support Saurabh Mehare by becoming a sponsor. Any amount is appreciated!