CSS Selectors
This section will learn about CSS Selectors
CSS selectors are patterns used to select and style specific HTML elements on a webpage. They are a fundamental part of CSS and allow you to target elements based on their type, class, ID, attributes, or even their relationship to other elements. Here’s a simple explanation and some examples suitable for beginners.
Basic CSS Selectors
Type Selector
- Selects all elements of a specific type (tag name).
Example: p selects all <p>
(paragraph) elements.
p {
color: blue;
}
- Class Selector
Selects elements with a specific class attribute.
Example: .highlight
selects all elements with the class "highlight".
.highlight {
background-color: yellow;
}
- ID Selector
Selects a single element with a specific ID attribute. Example: #main-header selects the element with the ID "main-header".
#main-header {
text-align: center;
font-size: 24px;
}
- Attribute Selector
Selects elements based on a specific attribute or attribute value.
Example: input[type="text"] selects all <input>
elements with a type of "text".
input[type='text'] {
border: 1px solid #ccc;
padding: 5px;
}
Advanced CSS Selectors
- Descendant Selector
Selects elements that are descendants of a specified element.
Example: div p selects all <p>
elements inside <div>
elements.
div p {
margin: 10px 0;
}
- Child Selector
Selects elements that are direct children of a specified element.
Example: ul > li
selects all <li>
elements that are direct children of <ul>
.
ul > li {
list-style-type: none;
}
- Pseudo-Class Selector
Selects elements based on their state or position.
Example: a:hover
selects <a>
elements when the user hovers over them.
a:hover {
text-decoration: underline;
}
Example code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSS Selectors Example</title>
<style>
/* Type Selector */
p {
color: blue;
}
/* Class Selector */
.highlight {
background-color: yellow;
}
/* ID Selector */
#main-header {
text-align: center;
font-size: 24px;
}
/* Attribute Selector */
input[type='text'] {
border: 1px solid #ccc;
padding: 5px;
}
/* Descendant Selector */
div p {
margin: 10px 0;
}
/* Child Selector */
ul > li {
list-style-type: none;
}
/* Pseudo-Class Selector */
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1 id="main-header">Welcome to CSS Selectors</h1>
<p>This is a simple example to understand CSS selectors.</p>
<p class="highlight">
This paragraph is highlighted using a class selector.
</p>
<div>
<p>This paragraph is inside a div.</p>
</div>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<a href="#">Hover over this link</a>
<br /><br />
<label for="name">Name:</label>
<input type="text" id="name" />
</body>
</html>