CSS: Types of Selectors
what is selectors?
CSS selectors allow you to target specific HTML elements. You can select elements by tag name (e.g., h1, p), class (e.g., .container, .button), ID (e.g., #header, #footer), or other attributes.
<!DOCTYPE html>
<html lang="en">
<head>
<title>My First WebPage</title>
<link href="./main.css" rel="stylesheet"></link>
</head>
<body>
<p>PARA 1</p>
<span>SPAN</span>
<p>PARA 2</p>
</body>
</html>
p {
color: red
}
...
<body>
<p id="header">HEADER</p>
<p>content</p>
</body>
...
#header {
color: red;
font-size: 24px;
}
index.html
...
<body>
<p class="highlight">Imp content</p>
<p>Normal content</p>
<p class="highlight">Imp content</p>
</body>
...
.highlight {
background-color: yellow;
}
selector:pseudo-class {
/* CSS rules */
}
index.html
...
<body>
<img class="my-image" src="https://img.freepik.com/free-photo/abstract-glowing-flame-drops-electric-illumination-generative-ai_188544-8092.jpg"></img>
</body>
...
.my-image:hover {
border: 10px solid purple;
scale: 1.2;
}
Pseudo-elements are used to add decorative effects or style specific parts of an element's content.
Syntax:
selector::pseudo-element {
/* CSS rules */
}
EX.
index.html
...
<body>
<p class="imp-first-line">Lorem ipsum .....</p>
</body>
...
.imp-first-line::first-line {
color: rgb(68, 75, 75);
font-size: 1.2rem;
font-weight: bold;
}
Syntax:
selector descendant-selector {
/* CSS rules */
}
main.css
div p {
/* CSS rules */
}
index.html
...
<body>
<ul class="menu">
<li>Home</li>
<li>About
<ul>
<li>History
<ul>
<li>2024</li>
<li>2023</li>
<li>2022</li>
</ul>
</li>
<li>Team</li>
</ul>
</li>
<li>Services</li>
<li>Contact</li>
</ul>
</body>
...
.menu ul li {
color: blue;
}
Syntax:
selector>direct-descendant-selector {
/* CSS rules */
}
index.html
...
<body>
<ul class="menu">
<li>Home</li>
<li>About
<ul>
<li>History
<ul>
<li>2024</li>
<li>2023</li>
<li>2022</li>
</ul>
</li>
<li>Team</li>
</ul>
</li>
<li>Services</li>
<li>Contact</li>
</ul>
</body>
...
.menu>li {
color: blue;
}
It allows you to select an element that is immediately preceded by another specific element. It targets an element that comes directly after another element, sharing the same parent.
selector+immediate-preceded-selector {
/* CSS rules */
}
EX.
index.html
...
<body>
<div>
<p>first para</p>
<p>second para</p>
<p>third para</p>
</div>
<p>Immediately preceded para</p>
<p>Not Immediately para</p>
</body>
...
div+p {
color: blue;
}
Syntax:
selector~immediate-preceded-selector {
/* CSS rules */
}
10. Attribute Selector
Comments
Post a Comment