CSS (Cascading Style Sheets) uses a specific syntax to apply styles to HTML elements. Understanding this syntax is crucial for writing effective and maintainable CSS code.
Basic Structure of CSS
A CSS rule consists of two main parts:
- Selector: This specifies the HTML element you want to style.
- Declaration Block: This contains one or more declarations separated by semicolons.
Each declaration includes:
- Property: The aspect of the element you want to change (e.g.,
color
,font-size
). - Value: The value you want to assign to the property (e.g.,
blue
,16px
).
Example of a CSS Rule
p { color: blue; font-size: 16px; }
In this example:
p
is the selector targeting all<p>
elements.color: blue;
is a declaration setting the text color to blue.font-size: 16px;
is a declaration setting the font size to 16 pixels.
Types of Selectors
CSS provides various types of selectors to target elements:
- Universal Selector (
*
): Targets all elements. - Type Selector (
h1
,p
,div
): Targets all elements of a specific type. - Class Selector (
.classname
): Targets elements with a specific class. - ID Selector (
#idname
): Targets an element with a specific ID. - Attribute Selector (
[type="text"]
): Targets elements with a specific attribute and value.
Grouping Selectors
Multiple selectors can be grouped together to apply the same styles to different elements:
h1, h2, h3 { color: green; }
This rule applies the color green to all <h1>
, <h2>
, and <h3>
elements.
Comments in CSS
Comments are used to explain the code and are ignored by browsers. They help make the CSS more readable and maintainable.
/* This is a comment */ p { color: red; /* This is an inline comment */ }
Cascading and Specificity
CSS stands for Cascading Style Sheets, which means that the order of the rules matters. When multiple rules apply to the same element, the rule with the highest specificity takes precedence.
Specificity hierarchy:
- Inline styles (e.g.,
style="color: red;"
) – Highest specificity. - ID selectors (e.g.,
#idname
). - Class selectors (e.g.,
.classname
), attribute selectors (e.g.,[type="text"]
), and pseudo-classes (e.g.,:hover
). - Type selectors (e.g.,
h1
,p
) and pseudo-elements (e.g.,::before
).
Important Rule
The !important
declaration can override any previous rule regardless of specificity:
p { color: blue !important; color: red; }
In this example, the text color will be blue because the !important
declaration takes precedence.
Summary
CSS syntax involves writing selectors to target HTML elements and applying styles through property-value pairs. Understanding the structure of CSS rules, the types of selectors, and the concept of specificity will help you create effective stylesheets.