Box model, specificity and modern layout
Predict box sizes, work out which CSS rule wins, and choose flexbox, grid and media queries with confidence.
Most CSS questions are prediction questions: how big is this box, which colour wins, where does this item go. Each has a rule you can apply step by step.
The box model
Every element is a box of content, padding, border and margin. With the default box-sizing: content-box, width sets only the content, so padding and border are added on top. A 200px box with 10px padding and a 5px border is 230px wide. With box-sizing: border-box, the 200px includes padding and border, which is why many projects set it on every element. Margin always sits outside and never counts towards the box width. Watch for margin collapse: two stacked block margins of 20px and 30px give a 30px gap, not 50px.
Specificity
When rules conflict, count each selector as (ids, classes/attributes/pseudo-classes, elements):
#main pis (1,0,1).card .titleis (0,2,0)ul li ais (0,0,3)
Compare from the left; one id beats any number of classes. Only when specificity is equal does the later rule win. Inline styles beat selectors, and !important overrides normal rules, so use it rarely or debugging becomes painful.
Flexbox and grid
Flexbox lays items out along one axis. justify-content aligns along the main axis and align-items along the cross axis; switching flex-direction to column swaps which is horizontal. flex: 1 lets items share leftover space. Grid handles two dimensions:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 16px;
}This one rule creates as many columns as fit and wraps the rest, often with no media query needed.
Responsive units and media queries
rem follows the root font size, em follows the element's own font size, and % follows the parent. Write base styles for small screens, then add @media (min-width: 768px) blocks for wider ones. Include <meta name="viewport" content="width=device-width, initial-scale=1"> or phones will render a zoomed-out desktop page.
Habit: before opening developer tools, write down what you expect the size or colour to be, then check. The gap between guess and result shows exactly which rule you need to revisit.
More in Web and app