Type Selector:
Type selector matches the HTML by using element name. For example to apply a style to h1 tag
1 2 3 4 5 6 7 8 |
<style> h1{ color:blue; } </style> <h1>This is heading</h1> <p>This is paragraph</p> <h1>This is another heading</h1> |
This style now applies to all h1 tag. What if you want to apply a style to only one h1 tag. We can then add two kinds of attributes to a tag class and id.
1 2 3 4 5 6 7 8 |
<h1>Class Selector:</h1> <p class="background">I want to add background to this</p> <p>This class has no background</p> <style> .background{ background-color:red; } </style> |
Here you define the value and same class can be used multiple times per page. The class value is now used as selector, starting with a period.
CSS class can be reused throughout the document. Whenever you give a class “background” to an element it will add a background color to the element.
Id Selector:
id selector is similar to class selector and it can be given any value and added to any element. However, id selector can be used just one per page and must have a unique value. The id selector value starts with #
1 2 3 4 5 |
<p id="background">I want to add background to this</p> <p>This class has no background</p> #background{ background-color:red; } |
Multiple Classes:
If you use space between class name that actially means that there are multiple classes as shown in the example below.
1 2 3 4 5 6 7 8 9 10 11 |
<div class="name address"></div> There are two classes name and address .name{ color:red; } .address{ font-size:16px; } .name.style{ font-weight:bold; } |
And if we combine both classes like shown below. Then that particular CSS will be applied when both classes are present
Note: Multiple IDs can not be used in the same HTML element
REF: You can test smaller snippets if code using an online tool JSfiddle