What I Learned Today at the Institute!
Every day after class, I work on my given tasks at the institute. Sometimes, Muthu Sir interacts with us, and today he asked a tricky question:
“In HTML, you can create 10
elements with the same class name. How would you style only the 5th using CSS?”At first, I was blank because I thought I had basic HTML & CSS knowledge, but I hadn’t deeply explored some tags and selectors before. This question made me curious, and I learned something new today!
What are Selectors?
Selectors are patterns used to target HTML elements. Once selected, you can style them using CSS or manipulate them using JavaScript.
Think of them like an “address” to find elements in your web page.
1. What are HTML Selectors?
- Selectors are used to find and target elements in your HTML.
- You use selectors in CSS to style elements or in XPath (mainly for testing/automation) to locate elements.
2. CSS Selector
- Used in CSS to apply styles.
- Example:
.myclass:nth-child(5) {
background: yellow;
}
This selects only the 5th element having the class myclass.
Types of Selectors & Explanation
a) Universal Selector (*)
- Targets all elements in the document.
* {
margin: 0;
padding: 0;
}
b) Type Selector (Tag name)
- Selects elements by their HTML tag name.
p {
color: blue;
}
- Changes the text color of all
tags.
c) Class Selector (.classname)
-Selects elements with a specific class.
html
<div class="box"></div>
css
.box {
background: yellow;
}
d) ID Selector (#idname)
- Selects a single element with a unique ID.
html
<h1 id="title">Hello</h1>
css
#title {
font-size: 24px;
}
e) Group Selector (,)
- Selects multiple elements at once.
css
h1, p, a {
font-family: Arial, sans-serif;
}
f) Descendant Selector (space)
- Selects elements inside another element.
css
div p {
color: red;
}
g) Child Selector (>)
- Selects only direct children. css
div > p {
font-weight: bold;
}
h) Pseudo-Class Selectors (:hover, :nth-child)
- Targets elements based on state or position.
.myclass:nth-child(5) {
background: yellow;
}
When to Use Which Selector?
- Use class when multiple elements share the same style.
- Use ID for unique elements.
- Use nth-child or pseudo-classes for special conditions.
- Use XPath (not CSS) when automating/testing to locate elements in the DOM.
Top comments (0)