Introduction
CSS (Cascading Style Sheets) is a powerful styling language that controls the visual presentation of web pages. Understanding its syntax and basic rules is crucial for creating well-structured and maintainable styles.
CSS Syntax
A CSS rule consists of three main parts:
- Selector: Specifies the HTML elements to style.
- Property: Defines the aspect of the element to change.
- Value: Assigns a specific style to the property.
Example:
p {
color: red;
font-size: 16px;
}
CSSHere:
p
is the selector (targets<p>
elements).color
andfont-size
are properties.red
and16px
are values.
CSS Selectors
Selectors define which HTML elements the styles apply to. Common selectors include:
- Element Selector: Targets all instances of an element.
h1 { color: blue; }
- Class Selector: Targets elements with a specific class.
.btn { background-color: green; }
- ID Selector: Targets a unique element with a specific ID.
#header { font-size: 24px; }
CSS Properties and Values
CSS properties control different aspects of an element’s appearance. Examples include:
- Text Styling:
color
,font-size
,font-weight
- Box Model:
margin
,padding
,border
- Positioning:
display
,position
,z-index
- Backgrounds:
background-color
,background-image
Example:
div {
width: 200px;
height: 100px;
background-color: yellow;
}
CSSCSS Comments
Comments help document your code and are ignored by browsers:
/* This is a CSS comment */
CSSCSS Case Sensitivity
CSS is case-insensitive, but class and ID names are case-sensitive:
/* Works */
.button {
color: blue;
}
/* Different from .Button */
CSSConclusion
Understanding CSS syntax is fundamental for effective web styling. Mastering selectors, properties, and values will help create visually appealing websites.