selector
selector
ID Selector(#):
a. For unique elements: An ID selector is used when you
need to select a single, unique element on a page. IDs
should be unique within a document, meaning that an
element with a particular id should only appear once.
b. Use the ID selector when you need to apply styles to a
very specific element, like a unique section, header, or
footer.
c. Example:
i. Html Code:
<div id="main-header">
<h1>Welcome to My Website</h1>
</div>
ii. CSS Code:
#main-header {
background-color: blue;
color: white;
}
iii. In this case, the #main-header selector targets only the
<div> with id="main-header", making it ideal for unique
elements like a single header, footer, or a specific section.
2. Class Selector(.):
a. Class selectors are used when you want to apply the
same style to multiple elements. You can apply a class to
many elements, allowing them to share the same styling.
b. Classes are perfect for styling groups of elements that
share a similar look, such as multiple buttons, cards, or list
items.
c. An element can have multiple classes, which allows you to
apply several styles to the same element.
d. Example:
i. HTML Code
<button class="btn">Click Me</button>
<button class="btn">Submit</button>
<button class="btn">Cancel</button>
ii. CSS Code
.btn {
background-color: green;
color: white;
padding: 10px;
}
• In this example, the .btn class is applied to all buttons
that need the same styling. You can reuse the class on
multiple elements.
3. Tag Selector:
a. Use tag selectors when you want to apply styles to all
elements of a particular type. Tag selectors are useful for
consistent styling of similar elements across a page (e.g.,
all paragraphs, all links, all headings).
b. Tag selectors are useful when you want to apply a style
globally to a specific element type, without needing to
assign a class or ID.
c. Example:
i. HTML Code
<p>This is a paragraph of text.</p>
<p>Here is another paragraph.</p>
ii. CSS Code
p{
font-size: 16px;
line-height: 1.5;
}
• Here, the p tag selector applies the same styles to all
<p> elements across the page. Similarly, you can style
all anchor tags (<a>) or headings (<h1>, <h2>, etc.)
using tag selectors.