Courses / CSS
1. CSS Selectors
CSS selectors are patterns used to select the elements you want to style.
How It Works
Think of CSS selectors like a filter that lets you choose which elements to style, similar to how a librarian selects specific books based on their genre.
Selectors identify elements based on their type, class, or ID.
Styles are applied to the selected elements.
The browser renders the styled elements on the page.
You can combine selectors for more specificity.
See It
The code styles all paragraphs to be blue, highlights one with a yellow background, and makes another bold. You could try changing the color of the unique paragraph to see the effect.
<!DOCTYPE html>
<html>
<head>
<style>
p { color: blue; }
.highlight { background-color: yellow; }
#unique { font-weight: bold; }
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p class="highlight">This paragraph is highlighted.</p>
<p id="unique">This is a unique paragraph.</p>
</body>
</html>Use It
Styling navigation menus based on user interaction.
<!DOCTYPE html>
<html>
<head>
<style>
nav a { color: black; }
nav a:hover { color: red; }
</style>
</head>
<body>
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</nav>
</body>
</html>Using CSS selectors allows for dynamic styling based on user actions, enhancing user experience.
Break It
What color will the highlighted paragraph be?
<!DOCTYPE html>
<html>
<head>
<style>
p.highlight { color: red; }
p { color: blue; }
</style>
</head>
<body>
<p class="highlight">This should be red.</p>
<p>This should be blue.</p>
</body>
</html>The highlighted paragraph is red because the more specific selector `.highlight` takes precedence over the general `p` selector.
To fix this, ensure that the more specific class selector comes after the general tag selector.
<!DOCTYPE html>
<html>
<head>
<style>
p { color: blue; }
p.highlight { color: red; }
</style>
</head>
<body>
<p class="highlight">This should be red.</p>
<p>This should be blue.</p>
</body>
</html>Level Up
Combinator Selectors: These allow you to select elements based on their relationship to other elements, like child or sibling relationships, providing more control over styling.
Attribute Selectors: These enable you to style elements based on specific attributes, allowing for more targeted styling.
Prove It
Create a CSS rule that styles all links inside a footer to have a gray color.
CSS
CSS Selectors
CSS selectors are used to select elements on a webpage to apply styles.
"I want to style specific elements without affecting everything else on the page."
CSS selectors are patterns that match HTML elements based on their attributes, types, or positions, allowing you to apply styles selectively.
"I want to style specific elements without affecting everything else on the page."
CSS selectors are patterns that match HTML elements based on their attributes, types, or positions, allowing you to apply styles selectively.