Selector in CSS
A CSS selector is a string that selects one or more HTML elements based on attributes like name, class, ID, or other properties. They are essential for determining which elements should be styled and how. The types of CSS selectors include the universal selector, element selector, ID selector, and class selector.
1. Universal Selector (*
)
The universal selector targets all elements on the web page. It applies styles to every element within the scope of the selector.
Example:
*{
color: #b92b27;
}
2. Element (Type) Selector
The element selector targets all instances of a specific HTML tag (element) on the page. It selects elements based on their tag name, like p
for paragraphs, h1
for headers, or div
for div containers.
Example: In this example, all the h3 tags are targeted
h3{
color: #b92b27;
}
3. ID Selector (#
)
The ID selector targets an HTML element with a specific id
attribute. Since the id
attribute should be unique within the HTML document, the ID selector only applies to one element.
Example: In this example, all the tags having the same id’s are targeted
#login{
background: gold;
}
#signup{
background-color: #b92b27;
color: aliceblue;
}
4. Class Selector (.
)
The class selector targets elements that have a specific class
attribute. Unlike id
, multiple elements can share the same class, allowing for reusable styling across different elements.
Example: In this example, all the tags having the same class are targeted
.follow{
background: rgb(196, 223, 27);
}
5. Grouping Selectors
You can group multiple selectors to apply the same styles to different elements, reducing redundancy.
Example: In this example, h1, h3, p tags are targeted
h1,h3,p,.follow,#login{
color: #b92b27;
}
Summary of Selectors:
Universal Selector (
*
): Targets all elements.Element Selector: Targets all instances of a specific HTML element.
ID Selector (
#
): Targets a specific element by its uniqueid
.Class Selector (
.
): Targets elements with a specific class, which can be applied to multiple elements.
ASSESSMENT C.1
Implement the following CSS for the given html document.
• Set font family of entire document to Courier New
• Set text color for all h1 headings to #1b74e4
• Set background color of search button to black & text to white
• Set background color of login & signup button to aqua.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Practice Qs</title>
</head>
<body>
<h1>GOOGLE</h1>
<button class="userbtn">Log in</button>
<button class="userbtn">Register</button>
<hr />
<label for="search">Search</label>
<input placeholder="search your query" id="search" />
<button id="searchbtn">Search</button>
</body>
</html>
HINT:
*{
font-family: 'Courier New', Courier, monospace;
}
h1{
color: #1b74e4;
}
#searchbtn{
background-color: black;
color: white;
}
.userbtn{
background: aqua;
}