Introduction to Layout in CSS - johnverz22/webdev1-lessons GitHub Wiki
CSS layout controls how elements are arranged on a webpage. It helps structure content, making it readable and visually appealing.
- Organizes content for better user experience.
- Ensures responsiveness on different screen sizes.
- Helps create structured and professional designs.
-
Block elements (
div
,p
,h1
, etc.) take up the full width. -
Inline elements (
span
,a
,strong
, etc.) only take up as much space as their content.
Example:
.block {
display: block;
background: lightblue;
padding: 10px;
}
.inline {
display: inline;
background: yellow;
padding: 5px;
}
<div class="block">I am a block element</div>
<span class="inline">I am inline</span>
Every HTML element is a box with:
- Content (text or image inside)
- Padding (space inside the border)
- Border (outline around the box)
- Margin (space outside the border)
Example:
.box {
width: 200px;
padding: 10px;
border: 2px solid black;
margin: 20px;
background: lightgray;
}
There are different ways to position elements:
- Static (default, follows normal flow)
- Relative (moves relative to its normal position)
- Absolute (positioned relative to its nearest positioned ancestor)
- Fixed (stays in place even when scrolling)
- Sticky (sticks at a certain position when scrolling)
Example:
.relative {
position: relative;
top: 20px;
left: 10px;
background: lightgreen;
padding: 10px;
}
<div class="relative">I am positioned relative</div>
Best for aligning items in a row or column.
Key Properties:
display: flex;
-
justify-content:
(align items horizontally) -
align-items:
(align items vertically) -
flex-wrap:
(wrap items on small screens)
Example:
.flex-container {
display: flex;
justify-content: space-between;
align-items: center;
background: lightblue;
padding: 10px;
}
.flex-item {
background: white;
padding: 20px;
border: 1px solid black;
}
<div class="flex-container">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
</div>
Best for complex layouts with rows and columns.
Key Properties:
display: grid;
-
grid-template-columns:
(define column sizes) -
grid-template-rows:
(define row sizes) -
gap:
(spacing between grid items)
Example:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
background: lightgray;
padding: 10px;
}
.grid-item {
background: white;
padding: 20px;
border: 1px solid black;
}
<div class="grid-container">
<div class="grid-item">Item 1</div>
<div class="grid-item">Item 2</div>
<div class="grid-item">Item 3</div>
<div class="grid-item">Item 4</div>
</div>
Use Case | Best Choice |
---|---|
Simple alignment | Flexbox |
Navigation bars | Flexbox |
Card layouts | Grid |
Full-page layout | Grid |
Centering content | Flexbox |