Home 〉 CSS Tutorials 〉 CSS Syntax and Selectors Explained with Examples | Beginners Guide
CSS Syntax and Selectors - Complete Guide with Examples !
Confused about how CSS targets HTML elements?
This guide demystifies CSS syntax and selectors, explaining how to write rules that apply styles to specific elements. Learn about different types of selectors like class, ID, and attribute selectors, and see practical examples that illustrate their usage.
CSS (Cascading Style Sheets) is used to style HTML elements on a web page. To understand CSS, the first thing you need to learn is its syntax and how to use selectors to apply styles.
A CSS rule is made of:
Example 📄
p {
color: red;
font-size: 16px;
}
Example 📄
selector {
property: value; /* one declaration */
another-property: value;
}
CSS selectors is used to target elements for styling.
For Example:
Example 📄
h1 {
color: blue;
}
This styles all '<h1>' headings.
<!DOCTYPE html>
<html>
<head>
<style>
label {
background-color: green;
}
.para {
background-color: yellow;
}
#para1 {
background-color: pink;
}
</style>
</head>
<body>
<label>This is a HTML label tag</label> <br>
<p class="para">This is a Paragraph</p>
<p id="para1">This is a Paragraph</p>
</body>
</html>
output 📌
This is a Paragraph
This is a Paragraph
You can Try the above code by changing the values in our user-friendly code editor by clicking the "Try It" button and see the output of the same.
Here, We have 5 different types of CSS Selector. Which are as follows:
We have covered linking and styling of CSS in our detailed blog post CSS Inline, Internal & External Styling | Add CSS to HTML Easily
Example 📄
/* This is a CSS comment */
Example 📄
<p style="color: green;">Inline styled paragraph</p>
Example 📄
<style>
body {
background-color: lightyellow;
}
</style>
Example 📄
<link rel="stylesheet" href="styles.css">
Understanding CSS syntax and selectors is the first step to mastering web design. By learning how to target elements correctly using element, class, ID, and group selectors, you'll be able to apply styles efficiently across your website. Keep your syntax clean, always close your declarations properly, and use comments to stay organized.
Yes! Use a comma to separate them. Example: 'h1, h2, p { margin: 10px; }'
IDs are unique and used once per page. Classes can be reused on multiple elements.
Yes, every CSS declaration should end with a semicolon ';'.
Yes. Example: '#header.button {}' targets an element with both 'id="header"' and 'class="button"'.