SELECTORS

Selectors

These are used to select the HTML elements for styling.

Element Selector :

  • This selector selects the HTML element by element name.

Example :

HTML

<div>
<h2>Hello There!</h2>
<p>How do you do?</p>
</div>

CSS

p {
color: orange;
}

This will produce the following result −

element-selector.png

id Selector :

  • This selector is used to select a particular HTML element by using id attribute.
  • This id should be unique for every element which you want to style.
  • To select an element with id name, write a # followed by id name(e.g. #idName).

Example :

HTML

<div>
<h2 id="greet">Hello There!</h2>
<p>How do you do?</p>
</div>

CSS

#greet {
color: red;
}

This will produce the following result −

id-selector.png

Class Selector :

  • This selector is used to select a HTML element by using class attribute.
  • Same class name can be used to style multiple elements.
  • To select an element with class name, write a . followed by class name(e.g. #className).
  • HTML elements can have more than one class.

Example :

HTML

<div>
<h2>Hello There!</h2>
<p class="text">How do you do?</p>
<h2 class="text">Hello World!</h2>
<p>Give the details</p>
</div>

CSS

.text {
color: lightgreen;
font-size: 18px;
}

This will produce the following result −

class-selector.png

Universal Selector :

  • The universal selector (*) selects all HTML elements on the page.
  • Generally used to remove default styles of a browser.

Example :

CSS

* {
padding: 0px;
margin: 0px;
box-sizing: border-box;
}

Pseudo classes

A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :hover can be used to change a box color when the user’s pointer hovers over it.

example : :hover :focus :first-child

//css
<style>
.hover-example {
width: 100px;
height: 100px;
background-color: limegreen;
color: white;
}
.hover-example:hover {
background-color: crimson;
width: 150px;
height: 150px;
}
input:focus {
background-color: yellow;
}
</style>
//html
<div class="hover-example">Hover your mouse over me</div>
<form>
First name: <input type="text" name="firstname">
</form>

selector specificity

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.

selector-specificity

Pseudo-element Selector

Pseudo-elements in CSS allows you to insert content onto a page without it needing to be in the HTML.While the end result is not actually in the DOM, it appears on the page as if it is.

example : ::before ::after ::first-letter

//CSS
<style>
div::before {
content: "before";
}
div::after {
content: "after";
}
p::first-letter {
font-weight: bold;
}
</style>
//HTML
<div>
before
<!-- rest of stuff inside the div -->
after
</div>
<p>
Lorem
</p>