HTML CSS - Syntax
CSS syntax consists of selectors and declarations. A selector targets specific HTML elements, and declarations contain the properties and values that define how those elements are styled. Understanding this syntax is key to applying CSS effectively and achieving the desired design.
Key Topics
Selectors
Example: A type selector targets all elements of a particular type, like <p>
.
p {
color: blue;
}
Properties and Values
Example: Each declaration includes a property (e.g., color
) and a value (e.g., red
).
h1 {
font-size: 24px;
color: red;
}
CSS Syntax in Action
This example demonstrates CSS syntax using a simple HTML page and a <style>
section. A code box is provided for the full sample.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" >
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>CSS Syntax Demo</title>
<style>
/* Selector: h1 targets all h1 elements */
h1 {
font-family: Arial;
color: purple;
}
/* Selector: .highlight targets elements with class="highlight" */
.highlight {
background: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<h1>CSS Syntax Example</h1>
<p>This paragraph is styled by the browser's defaults.</p>
<p class="highlight">This paragraph uses a custom class selector that highlights its text.</p>
</body>
</html>
Explanation: In this example, the h1
selector targets all <h1>
elements, applying a purple color and a font family. The .highlight
class selector applies a yellow background and bold text to any element with that class. Understanding selectors, properties, and values is foundational to writing effective CSS.
Key Takeaways
- CSS syntax is based on selectors, properties, and values.
- Selectors target HTML elements, classes, or IDs.
- Properties and values define how selected elements are displayed.
- Use class selectors for reusable styles and type selectors for broad styling.
- Mastering CSS syntax is essential for precise and maintainable styling.