CSS Syntax
CSS (Cascading Style Sheets) is used to style HTML elements. It consists of selectors and declarations.
CSS Rule Syntax
A CSS rule consists of a selector and a declaration block:
selector {
property: value;
}
Selector
The selector targets the HTML element(s) you want to style. It can be an element selector, class selector, ID selector, attribute selector, or a combination of these.
/* Element Selector */
h1 {
color: blue;
}
/* Class Selector */
.example {
background-color: #f0f0f0;
}
/* ID Selector */
#main-content {
font-size: 18px;
}
/* Attribute Selector */
a[target="_blank"] {
color: red;
}
Declaration Block
The declaration block contains one or more declarations separated by semicolons. Each declaration includes a CSS property name and its corresponding value.
p {
color: green;
font-size: 16px;
}
Comments in CSS
You can use comments in CSS to explain sections of your code. Comments start with /*
and end with */
.
/* This is a comment in CSS */
p {
margin-bottom: 20px; /* Adding space below paragraphs */
}
Multiple Selectors
You can apply the same styles to multiple selectors by separating them with commas.
h1, h2, h3 {
font-family: Arial, sans-serif;
}
Inline CSS
You can also apply styles directly to HTML elements using the style
attribute.
<h1 style="color: purple; font-size: 24px;">Hello, CSS!</h1>
External CSS
For larger projects, it’s common to use an external CSS file linked to your HTML document using the <link>
element.
<link rel="stylesheet" href="styles.css">