CSS Selectors

Selector in CSS

CSS Selectors are used <em>to select the content you want to style</em>. Selectors are the part of CSS rule set.

There are several different types of selectors in CSS.

  1. Class Selector
  2. Descendant Selectors
  3. Group Selector
  4. Type Selector
  5. Id Selector

i) Type Selector:

 The most common and easy to understand selectors are type selectors. This selector targets element types on the page.

Example:

p {
   color: red;
   font-size:130%;
} 

ii)Id Selector:

id selectors allow you to style an HTML element that has an id attribute, regardless of their position in the document tree.

It is written with the hash character (#), followed by the id of the element.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
    text-align: center;
    color: blue;
}
</style>
</head>
<body>
<p id="para1">Hello World</p>
</body>
</html>  

iii)Class Selector:

Class selectors work in a similar way. The major difference is that IDs can only be applied once per page, while classes can be used as many times on a page as needed.

Note: A class name should not be started with a number.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
.center {
    text-align: center;
    color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is forestgreen & aligned center.</h1>
<p class="center">This paragraph is forestgreen & aligned center.</p> 
</body>
</html>

iv)Descendant Selectors:

These selectors are used to select elements that are descendants of another element. When selecting levels, you can select as many levels deep as you need to.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
#intro .first em {
   color: pink; 
   background-color:gray;
}
</style>
</head>
<body>
<div id="intro">
  <p class="first">This is a  <em> paragraph.&lt/em> </p>
   <p> This is the second paragraph. </p>
</div>
<p class="first"> This is not in the intro section. </p>
<p> The second paragraph is not in the intro section.  </p>
</body>
</html>  

v) Group Selector :

The grouping selector in CSS Selectors is used to select all the elements with the same style definitions.

Grouping selector is used to minimize the code. Commas are used to separate each selector in grouping.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
    text-align: center;
    color: orange;
}
</style>
</head>
<body>
<h1>Hello Learner's</h1>
<h2>Hello Learner's (In smaller font)</h2>
<p>This is a paragraph.</p>
</body>
</html>


Recommended Posts :-

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *