CSS selectors are the primary means by which CSS “finds” HTML values. Selectors are patterns used to select the HTML elements you want to style.
<p>
elements in an HTML document:p {
color: blue;
}
<p class="highlight">This is a highlighted paragraph.</p>
.highlight {
background-color: yellow;
}
<div id="main-content">This is the main content.</div>
#main-content {
width: 80%;
}
Attribute selectors allow you to select elements based on their attributes and attribute values.
<input type="text">
input[type] {
border: 1px solid gray;
}
<a href="https://example.com">Visit Example</a>
a[href="https://example.com"] {
color: green;
}
As shown in the selector examples above, direct selection is the most straightforward way. You define a selector in your CSS and apply styles directly to the selected elements.
<div class="parent">
<p>This is a paragraph inside the parent div.</p>
</div>
.parent p {
font-size: 16px;
}
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
ul > li {
list-style-type: square;
}
Pseudo-classes are used to define a special state of an element. For example, the :hover
pseudo-class applies styles when the user hovers over an element.
<a href="#">Hover me</a>
a:hover {
text-decoration: underline;
}
Classes are great for creating reusable styles. You can define a class in your CSS and apply it to multiple HTML elements.
.button {
background-color: #007BFF;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
<button class="button">Submit</button>
<a href="#" class="button">Learn More</a>
IDs are used for elements that are unique on a page. For example, the main header of a page can have an ID.
<header id="main-header">
<h1>My Website</h1>
</header>
#main-header {
background-color: #333;
color: white;
padding: 20px;
}
You can group selectors to apply the same styles to multiple elements.
h1, h2, h3 {
font-family: Arial, sans-serif;
}
Aim for a good balance in selector specificity. Overly specific selectors can make your CSS hard to maintain, while too general selectors may not target the elements you want accurately.
Semantic HTML tags like <header>
, <nav>
, <main>
, <article>
, and <footer>
make it easier to select elements with CSS. For example, you can target the main content area using the <main>
tag.
<main>
<p>This is the main content of the page.</p>
</main>
main {
margin: 20px;
}
Inline styles have the highest specificity and can make your code hard to manage. It’s better to keep your styles in external CSS files or in <style>
tags within the HTML document.
Understanding how CSS finds HTML values is essential for effective web styling. By mastering selectors, combinators, pseudo-classes, and following common and best practices, you can create well-structured and maintainable CSS code. Whether you are a beginner or an experienced developer, these techniques will help you style your web pages more efficiently and achieve the desired visual effects.