So far, in past chapters we have applied styles to body and div like below:
<div>
div{
width : 200px;
}
Here,
div -> selector
width -> property-name
200px -> property-value
CSS rule syntax
So the basic syntax for applying CSS rule is
selector{
property-name : property-value;
}
Selectors
Now, let us see what types of selectors are available in CSS.
Tag name Selectors
You can apply style to any HTML tag, just by mentioning the tag name.
For e.g.,
HTML snippet
<body>
<div>
Hello world! Welcome to this tutorial page.
</div>
</body>
In the above HTML snippet, we can apply style to <body>tag as
body{
Background-color : #e1e1e1;
}
ID Selector
ID selector is used to apply styles to an element with specific ID attribute in HTML tag.
Syntax:
#<element_id>
HTML snippet:
<body>
<div>
Hello world! Welcome to this tutorial page.
</div>
<div id="mystyle">
This is the div where the CSS style is applied based on ID selector!
</div>
</body>
CSS snippet:
#mystyle{
background-color : #d1d1d1;
}
Output:
The background color will be applied only to the div with id attribute as “mystyle”.
Class Selector
Class selector is used to apply styles to an element with specific class attribute in HTML tag.
Syntax:
.<class_name>
HTML snippet:
<body>
<div>
Hello world! Welcome to this tutorial page.
</div>
<div class="class1">
This is the div where the CSS style is applied based on class selector .class1
</div>
<div id="mystyle">
This is the div where the CSS style is applied based on ID selector #mystyle!
</div>
</body>
CSS snippet:
.class1{
background-color : #aaa;
}
Output:
The background color (#aaa) will be applied to the div with class name as “class1”.
Grouping selectors
You can apply same style for multiple selectors by comma (,) separator.
HTML snippet:
<body>
<div>
Hello world! Welcome to this tutorial page.
</div>
<div class="class1">
This is the div where the CSS style is applied based on class selector .class1
</div>
<div id="mystyle">
This is the div where the CSS style is applied based on ID selector #mystyle!
</div>
</body>
CSS snippet:
.class1, #mystyle{
background-color : #aaa;
}
Output:
The background color (#aaa) and padding will be applied to both the div with class name as “class1” and the div with id as “mystyle”.