Reference article · Programming
CSS: box model, Flexbox and Grid
CSS applies presentation rules to HTML. Understanding each box helps diagnose unexpected spacing, overflowing columns and layouts that fail on small screens.
Content, padding, border and margin
Padding and border surround content; margin separates boxes. With content-box, width measures content and padding and borders add to it. With border-box, the declared width includes content, padding and border; margin remains outside.
.card {
box-sizing: border-box;
width: 300px;
padding: 16px;
border: 1px solid #888;
}Flexbox for a row or column
display: flex makes direct children flex items. flex-direction determines the main axis. justify-content distributes space along that axis; align-items aligns across it. flex-wrap allows items to move onto another line.
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
}Grid for rows and columns
Grid defines a two-dimensional layout. repeat and minmax avoid writing each column individually. This creates as many columns as fit, with a minimum that cannot exceed the container width.
.list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 240px), 1fr));
gap: 16px;
}Adaptation and real content
Try long titles, one card and many cards. A fixed width can suit a component without making the whole page responsive. Avoid visual rearrangements that make keyboard order confusing.
Inspection exercise
- Create three cards inside a container with class list.
- Narrow the window and observe the column count.
- Inspect a card in browser developer tools and identify its content, padding, border and margin.
References
Related articles
- Fundamentals: variables, conditions and loops
- Semantic HTML and page structure
- JavaScript: functions, parameters and scope
- JavaScript: arrays, objects and data transformations
- DOM and events: connect JavaScript to HTML
- Promises, async/await and fetch requests
- HTTP and web APIs: requests, responses and status codes
- JSON: format, parsing and data validation
- Git: changes, commits, branches and remotes
- Node.js and npm: project scripts and dependencies
- Debugging and tests: finding and checking errors
- Colour formats: HEX, RGB and HSL
- UUID identifiers
- Random values in JavaScript
