CSS (Cascading Style Sheets) follows a specific syntax to define styles for HTML elements. A CSS rule consists of a selector and a declaration block.
Basic CSS Rule
selector {
property: value;
}
For example:
h1 {
color: blue;
font-size: 24px;
}
Parts of CSS Syntax
- Selector: Defines which HTML element the style applies to (e.g.,
h1
,p
,.class
). - Property: The style attribute you want to change (e.g.,
color
,font-size
). - Value: The setting for the property (e.g.,
blue
,16px
).
Example with Multiple Declarations
p {
color: #333;
line-height: 1.5;
font-family: Arial, sans-serif;
}
Selectors in CSS
CSS provides different types of selectors:
- Element Selector: Targets an HTML element.
h1 { color: red; }
- Class Selector: Targets elements with a specific class, prefixed by a dot (
.
).
.highlight { background-color: yellow; }
- ID Selector: Targets a unique element with an ID, prefixed by a hash (
#
).
#main-title { font-size: 32px; }
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Syntax Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="main-title">Hello, World!</h1>
<p class="highlight">This is a CSS syntax tutorial.</p>
</body>
</html>
CSS (style.css):
#main-title {
color: darkblue;
text-align: center;
}
.highlight {
background-color: yellow;
padding: 10px;
}
Conclusion
CSS syntax is simple yet powerful. By combining selectors, properties, and values, you can create professional, responsive, and visually appealing websites.