CSS Selector
CSS Selector
Selector are used for select an Html element it is select by name, id, class etc.
- id selector
- class selector
- Element Selector
- Group Selector
- Universal Selector
Element Selector
It is used to select an Html elements by name.
Example
<html> <body> <style> h1{ color: red; font-size: 18px; } p{ color: red; font-size: 18px; } </style> <h1>This is h1 heading</h1> <p>This is paragraph</p> </body> </html>
Result
This is h1 heading
This is paragraph
id Selector
The id selector is used to specify a style for a single, unique element. The id selector uses the id attribute of the Html element, and is defined with a "#".
In below example we apply css on <p> tag with id="para1":
Syntax
#para1 { text-align:center; color:red; }
Example
<html> <body> <style> #center { text-align:center; } </style> <h1 id="center">This is heading</h1> <p id="center">This is paragraph</p> </body> </html>
Result
This is heading
This is paragraph
Note: Do not start an ID name with a number. Because It will not work in Mozilla/Firefox browser.
class Selector
The class selector is used to specify a style for a group of elements. Unlike the id selector. This allows you to set a particular style for many Html elements with the same class. The class selector uses the Html class attribute, and is defined with a "."
In below example declare a class with name "center" (.center) which is used many Html attribute for dispaly that particluta element in center
Syntax
.center { text-align:center; }
Example
<html> <body> <style> .center { text-align:center; } </style> <h1 class="center">This is heading</h1> <p class="center">This is paragraph</p> </body> </html>
Result
This is heading
This is paragraph
You can also specify only specific Html elements should be affected by a class. In below example , all <p> elements will be display in center because here we apply css with <p> tag.
Example
p.center {text-align:center;}
Note: Do not start a class name with a number. This is only supported in Internet Explorer.
By using group selector you can apply same style of number of Html elements.Grouping selector is used to minimize the code. Here commas are used to separate each selector in grouping.
Example
<html> <body> <style> h1 h2, p{ color: red; font-size: 18px; } </style> <h1>This is h1 heading</h1> <h2>This is h2 heading</h2> <p>This is paragraph</p> </body> </html>
Result
This is h1 heading
This is h2 heading
This is paragraph
Universal Selector
The universal selector is used to selects all the elements on the pages.
Example
<html> <body> <style> * { color: red; font-size: 18px; } </style> <h1>This is h1 heading</h1> <h2>This is h2 heading</h2> <p>This is paragraph</p> </body> </html>
Result
This is h1 heading
This is h2 heading
This is paragraph