Tuesday, March 11

How would you define Id and Class Selectors in CSS

CSS allows us  to specify our own selectors called "id" and "class" to setting a style  for a HTML element.The id selector is used to specify a style for a single or unique element,where the class selector is used to specify a style for a group of elements.


ID Selectors

ID selector uses the id attribute of the HTML element to apply a style.It is used to specify a style for a single, unique element.It is defined with a "#".


Example :

To define style using ID Selector use the code bellow :
<html>
<head>
<style>
#text1
{
text-align:right;
color:black;
} 
</style>
</head>

<body>
<p id="text1">Using ID Selector</p>
<p>Without using ID Selector</p>
</body>
</html>

Class Selector:

Class selector is used to specify a style for a group of HTML elements.It is defined with a ".".


Example :

To define style using ID Selector use the code bellow :
<html>
<head>
<style>
.text1
{
color:red;
} 
</style>
</head>

<body>
<h1 class="text1">Using Class Selector</h1>
<p class="text1">Using Class Selector</p> 
<p>Without using Class Selector</p>
</body>
</html>


You can also set style for only a specific HTML elements by a class. The syntax for this is :
p.text1 {color: red;} 

Example :

To define style using ID Selector use the code bellow :
<html>
<head>
<style>
p.text1
{
color:red;
} 
</style>
</head>

<body>
<h1 class="text1">It will not be affected</h1>
<p class="text1">It will be affected</p> 
</body>
</html>


If you have any questions related to this feel free post your problem on comment box.Thank you.