Introduction to CSS Syntax
CSS (Cascading Style Sheets) syntax consists of rules that define the appearance of elements on a web page. Each rule contains a selector, properties, and values that control the styling of HTML elements.
Basic CSS Syntax Structure
The structure of a CSS rule includes a selector, a declaration block, and one or more declarations:
property: value;
property: value;
}
In this structure:
- Selector: Identifies the HTML element(s) to style, like
p
for paragraphs orh1
for headings. - Property: Specifies what aspect of the element to style, like
color
orfont-size
. - Value: Sets the effect for the property, like
blue
or16px
.
Example of a CSS Rule Set
color: blue;
font-size: 24px;
text-align: center;
}
CSS Selectors
Selectors determine which HTML elements the CSS rules will apply to. Here are some common types of selectors:
- Element Selector: Targets all instances of a specific HTML element, like
p
orh1
. - Class Selector: Targets elements with a specific class, using a dot (.) prefix. Example:
.intro
. - ID Selector: Targets a unique element with a specific ID, using a hash (#) prefix. Example:
#header
. - Universal Selector: Targets all elements using the asterisk (*). Example:
* { margin: 0; }
. - Group Selector: Targets multiple selectors with the same style, separated by commas. Example:
h1, h2, h3 { color: darkblue; }
.
CSS Properties and Values
CSS properties control the style of HTML elements, while values define how those properties are applied. Here are some common CSS properties:
- color: Sets the text color. Example:
color: red;
- background-color: Sets the background color. Example:
background-color: yellow;
- font-size: Sets the size of the font. Example:
font-size: 20px;
- margin: Sets the outer space around an element. Example:
margin: 10px;
- padding: Sets the inner space inside an element. Example:
padding: 10px;
Example with Multiple Properties
color: darkgray;
font-size: 18px;
padding: 10px;
background-color: #f0f0f0;
}
Adding Comments in CSS
Comments in CSS help you explain or organize your code. They start with /*
and end with */
.
p {
color: black;
}
Summary
CSS syntax allows you to target HTML elements and style them with properties and values. Understanding selectors, properties, and values is essential for writing effective CSS code and creating visually appealing web pages.