– How CSS Rules are Written and Applied
CSS (Cascading Style Sheets) is the language used to style HTML elements, but understanding its syntax and how stylesheets work is key to mastering web design.
In this blog, we’ll explore:
- The basic syntax of CSS rules
- Using single and multiple stylesheets
- Different ways to define value lengths and percentages in CSS
The Basic CSS Syntax
CSS rules follow a simple structure made up of selectors, properties, and values.
css
CopyEdit
selector {
property: value;
}
- Selector: Targets the HTML element(s) you want to style (e.g., p, .class-name, #id)
- Property: The style attribute you want to change (e.g., color, font-size, margin)
- Value: The setting for the property (e.g., red, 16px, 10%)
Example:
css
CopyEdit
p {
color: blue;
font-size: 16px;
}
This rule styles all paragraph <p> elements with blue text and font size of 16 pixels.
Single Stylesheet vs Multiple Stylesheets
- Single Stylesheet: All CSS rules are stored in one .css file, which is linked to your HTML page.
html
CopyEdit
<link rel=”stylesheet” href=”styles.css”>
This keeps your site’s styling centralized and easy to maintain.
- Multiple Stylesheets: You can link more than one stylesheet in your HTML if you want to separate styles by purpose, device, or section.
html
CopyEdit
<link rel=”stylesheet” href=”reset.css”>
<link rel=”stylesheet” href=”layout.css”>
<link rel=”stylesheet” href=”colors.css”>
This allows modular design but requires careful management to avoid conflicting styles.
CSS Value Lengths and Percentages
CSS supports various units to define size, spacing, and positioning:
Common Length Units
Unit | Description | Example |
px | Pixels — fixed size | font-size: 16px; |
em | Relative to the font size of the element | margin: 2em; |
rem | Relative to the root font size | padding: 1.5rem; |
% | Percentage relative to parent or container | width: 50%; |
vw | Viewport width (1% of viewport width) | width: 80vw; |
vh | Viewport height (1% of viewport height) | height: 100vh; |
When to Use Percentages vs Fixed Units
- Percentages (%) are flexible and responsive — they adjust relative to parent containers.
- Pixels (px) are fixed sizes — good for precise control but less flexible on different screens.
- Relative units (em, rem) help create scalable designs that adapt to user preferences.
Important Notes
- The order of linked stylesheets matters — later stylesheets can override earlier ones (cascading effect).
- Using multiple stylesheets wisely helps organize CSS but avoid unnecessary duplication.
- Choose units based on your design goals: fixed vs flexible and responsive layouts.
Conclusion
Understanding CSS syntax and how stylesheets work is fundamental to writing clean, maintainable styles. Using the right units for values ensures your designs look great on all devices.
“CSS lets you paint your webpage with style — mastering its syntax is the first brushstroke.”