CSS Selectors
Basic Selectors (Element, ID, Class)
Basic selectors target elements directly:
- Element Selector: Selects all instances of a tag (e.g.,
p
,div
). - ID Selector: Selects a single element using
#id
. - Class Selector: Selects elements with a specific class using
.class
.
<style>
p {
color: blue;
}
#main-heading {
font-size: 24px;
}
.highlight {
background-color: yellow;
}
</style>
<h1 id="main-heading">Welcome</h1>
<p>This is a paragraph.</p>
<p class="highlight">This is a highlighted paragraph.</p>
Welcome
This is a paragraph.
This is a highlighted paragraph.
Grouping and Universal Selector
Grouping Selector (,
): Targets multiple selectors at once.
Universal Selector (*
): Applies to all elements.
<style>
h2, p {
color: darkgreen;
}
* {
font-family: Arial, sans-serif;
}
</style>
<h2>Grouped Selector</h2>
<p>Paragraph with grouped styling.</p>
<div>This div has default font from universal selector.</div>
Grouped Selector
Paragraph with grouped styling.
Combinators (descendant, child, sibling)
CSS provides combinators to select elements based on their relationship:
- Descendant (
div p
): Targetsp
insidediv
. - Child (
div > p
): Targets only direct children. - Adjacent sibling (
h2 + p
): Targets firstp
afterh2
. - General sibling (
h2 ~ p
): Targets allp
s afterh2
.
<style>
div p {
color: blue;
}
div > p {
font-weight: bold;
}
h2 + p {
background-color: #f9f9a0;
}
h2 ~ p {
font-style: italic;
}
</style>
<div>
<p>Direct child of div</p>
<section>
<p>Descendant inside section</p>
</section>
</div>
<h2>Heading</h2>
<p>This is adjacent sibling.</p>
<p>This is general sibling.</p>
Direct child of div
Descendant inside section
Heading
This is adjacent sibling.
This is general sibling.
Attribute Selectors
Attribute selectors allow you to style elements based on the presence or value of attributes.
<style>
input[type="text"] {
border: 2px solid green;
}
a[target="_blank"] {
color: red;
}
</style>
<input type="text" placeholder="Text input">
<input type="password" placeholder="Password input">
<a href="#" target="_blank">Open in new tab</a>
Pseudo-classes and Pseudo-elements
Pseudo-classes style elements based on user interaction or element state.
Pseudo-elements style specific parts of an element.
<style>
a:hover {
color: orange;
}
p::first-line {
font-weight: bold;
}
p::before {
content: "👉 ";
}
</style>
<a href="#">Hover over me</a>
<p>This is a paragraph demonstrating pseudo-elements.</p>
👉 This is a paragraph demonstrating pseudo-elements.
If you have any questions, feel free to ask. Thank you for reading!
If you have any query or question, please contact through below form. Our team will be in touch with you soon.
Please provide your valueable feedback or suggession as well.