CSS Syntax and Selectors
Basic Syntax
CSS (Cascading Style Sheets) syntax is composed of a set of rules. These rules are formed by combining selectors and declarations.
- Selector: This targets the HTML element that you want to style.
- Declaration: This is a single rule like setting a color or font. A declaration is split into a property and a value.
- Property: This is the type of style that you want to apply (e.g., color, font-size, margin).
- Value: This specifies the setting you want to apply to the property (e.g., red, 12px, auto).
A CSS rule looks like this:
selector {
property: value;
}
For example:
p {
color: red;
font-size: 14px;
}
In this example, p
is the selector, and there are two declarations: one for color
and one for font-size
.
Type, Class, and ID Selectors
- Type Selector: Targets HTML elements of a specific type. For instance,
p
selects all<p>
elements. - Class Selector: Targets elements with a specific class attribute. It’s preceded by a period (.) symbol. For example,
.myclass
targets all elements withclass="myclass"
. - ID Selector: Targets a unique element with a specific id attribute. It’s preceded by a hash (#) symbol. For instance,
#myid
selects the element withid="myid"
.
Example with Result Output
Let’s apply different selectors in an HTML document.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<style>
/* Type Selector */
p {
color: blue;
}
/* Class Selector */
.highlight {
background-color: yellow;
}
/* ID Selector */
#special {
font-size: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<p>This is a normal paragraph.</p>
<p class="highlight">This paragraph has a yellow background.</p>
<p id="special">This is a special paragraph.</p>
</body>
</html>
Conclusion
Understanding CSS syntax and the use of different selectors is fundamental for effective styling. Selectors allow you to target specific elements in your HTML document to apply styles. As you progress, you’ll learn about more complex selectors and how they can be combined for more sophisticated styling.
In the next tutorial, we will explore how to use CSS for styling colors, backgrounds, and borders.