CSS Basics: Styling the Web
CSS (Cascading Style Sheets) describes how HTML elements are to be displayed on screen, paper, or in other media.
1. Syntax
A CSS rule consists of a selector and a declaration block.
/* Selector */
h1 {
color: blue; /* Property: Value; */
font-size: 24px; /* Property: Value; */
}
2. Selectors
Selectors match the HTML elements you want to style.
- Element Selector: Selects all elements of a given type.
css p { color: red; } - Class Selector (
.): Selects elements with a specific class attribute. (Most Common)css .btn { background-color: green; } - ID Selector (
#): Selects a unique element with a specific id attribute.css #header { height: 60px; }
3. The Box Model (Crucial Concept)
Every element on a web page is a rectangular box.
- Content: The actual content (text, image).
- Padding: Space between the content and the border (inside).
- Border: A border that goes around the padding and content.
- Margin: Space outside the border (distance from other elements).
div {
width: 300px;
padding: 20px;
border: 1px solid black;
margin: 10px;
}
4. Layout (Flexbox)
Modern layout is mostly done using Flexbox.
.container {
display: flex; /* Enables Flexbox */
justify-content: center; /* Horizontally centers items */
align-items: center; /* Vertically centers items */
}