CSS Basics
1. CSS Syntax
CSS syntax consists of selectors and declarations. A CSS rule is composed of a selector and a declaration block.
Syntax:
selector { property: value;}- Selector: Specifies which HTML element(s) you want to style.
- Property: Defines the style you want to apply (e.g., color, font-size).
- Value: Specifies the value of the property (e.g., red, 16px).
Example:
h1 { color: blue; font-size: 24px;}This rule will apply blue color and 24px font size to all <h1> elements.
2. Selectors
Selectors are used to target specific HTML elements.
- Universal Selector (
*): Targets all elements. - Element Selector (
h1): Targets elements of a specific type. - Class Selector (
.class-name): Targets elements with a specific class. - ID Selector (
#id-name): Targets an element with a specific ID.
Example:
/* All elements */* { margin: 0; padding: 0;}
/* Class selector */.button { background-color: red;}
/* ID selector */#header { font-size: 32px;}3. CSS Properties
CSS properties define the styles applied to the HTML elements. Some common properties include:
color- Sets the color of text.background-color- Sets the background color.font-size- Defines the size of the text.margin- Adds space outside the element.padding- Adds space inside the element.border- Adds a border around the element.display- Defines how an element is displayed on the page.width & height- Define the size of an element.
Example:
/* Text color */p { color: red;}
/* Background color */div { background-color: yellow;}
/* Box model */div { margin: 20px; padding: 10px; border: 2px solid black;}4. Comments
Comments in CSS are added using /* */ syntax and are ignored by the browser.
Example:
/* This is a comment */h1 { color: green; /* Inline comment */}