CSS Selectors

Selector

A selector helps us to know exactly for which element we want to add a given style.

Internal CSS Output

In the diagram above, we are applying green colour for all the <p> tags. This type of selector is called Element selector [also known as tag or type selector]. If you need to style a different element, say <h1>, just change the selector name in CSS.

CSS Selectors

There are many types of selectors. Following are the three mostly used selectors:

Selector nameDescriptionExample
1. Element selectorUnder this category, we define a common style for an individual html tag and it reflects same style for that tag, wherever it is used.p {

  color: green;

}

This will reflect green colour for all the p tags.

2. ID selectorUnder this category, we give ID to any html tag, and for that ID we define a style. Same ID cannot be assigned to multiple HTML tags; hence it is mostly used in case unique style is needed for a specific HTML element.

In CSS, we define it using hash-symbol (#).

CSS:
#my-id1 {

  color: green;

}
HTML:

<p id=”my-id1″>

This will reflect green colour for any html tag which has ID equal to “my-id1”.

3. Class selectorUnder this category, we define a class for any html tag, and for that class we define a style. It is the most used CSS selector because same class can be assigned to multiple html tags, hence a CSS style can be reused.

In CSS, we define it using a dot(.).

CSS:
.my-class {

  color: green;

}
HTML:

<p class=”my-class1″>
This will reflect green colour for any html tag which has class equal to “my-class1”.

 

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.