Introduction to CSS
CSS (Cascading Style Sheets) describes how HTML elements are displayed. HTML provides structure while CSS provides presentation.
- Improves webpage appearance
- Separates content from presentation
- Reduces code duplication
- Easy maintenance
- Faster development
- Consistent design
Analogy: HTML = Bricks & Walls, CSS = Paint & Decoration.
Ways to Apply CSS
- Inline CSS
- Internal CSS
- External CSS (Recommended)
<h1 style="color:red">Inline CSS</h1>
<style>
h1{color:blue;}
</style>
<link rel="stylesheet" href="style.css">
Basic CSS Syntax
selector{
property:value;
}
Basic CSS Selectors
| Selector | Example | Purpose |
|---|---|---|
| Element | h1{color:red;} | Styles all matching elements |
| ID | #special{...} | Styles unique element |
| Class | .box{...} | Styles multiple elements |
Span is an inline element used to style a small portion of text.
<p>This is a <span style="color:red;">red</span> word.</p>
Important CSS Properties
| Property | Purpose |
|---|---|
| color | Text color |
| background-color | Background color |
| font-size | Text size |
| font-family | Font family |
| text-align | Alignment |
| border | Border |
| width/height | Dimensions |
| margin/padding | Spacing |
| display | Layout |
| position | Positioning |
| border-radius | Rounded corners |
Colors
- Named colors
- RGB
- RGBA
- Hexadecimal (#RRGGBB - most common)
h1{
color:white;
background:blue;
border:solid red 5px;
border-radius:10px;
}
Display Property
Defines how an element is displayed.
| Value | Description |
|---|---|
| block | New line, full width |
| inline | Same line |
| inline-block | Inline with width/height |
| none | Hidden |
| flex | One-dimensional layout |
| grid | Two-dimensional layout |
Position Property
| Value | Purpose |
|---|---|
| static | Default |
| relative | Relative to original position |
| absolute | Relative to nearest positioned ancestor |
| fixed | Fixed during scrolling |
| sticky | Acts normal then sticks |
Removing an element from the normal flow means other elements occupy its original space.
List & Table Properties
list-style-type: disc, circle, square, none
ul{
list-style-type:square;
}
border-collapse merges adjacent table borders.
table{
border-collapse:collapse;
}
Background Images
body{
background-image:url("image.jpg");
background-repeat:no-repeat;
background-size:cover;
}
- cover - fills screen
- contain - entire image visible
- 100% 100% - stretches image
Other Properties
img{ border:groove 10px blue; }
button{ cursor:pointer; }
.hidden{ visibility:hidden; }