Skip to main content

CSS: Styling and Layout

CSS selects elements and applies styles to them.

/* selector { property: value; } */
h1 {
color: #1f2937;
font-size: 2rem;
}

.card {
padding: 1rem;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
}

#hero > p:first-child {
font-weight: 600;
}

Selectors​

SelectorMatches
pElement type
.cardClass
#heroID
a[target="_blank"]Attribute
ul liDescendant
ul > liDirect child
a:hover, li:nth-child(2)Pseudo-class
p::first-linePseudo-element

Cascade and specificity​

When rules conflict: importance (!important), then specificity (inline > ID > class/attribute/pseudo-class > element), then source order. Prefer classes and keep specificity low.

The box model​

margin -> border -> padding -> content
*, *::before, *::after {
box-sizing: border-box; /* width includes padding and border */
}

Flexbox (one dimension)​

.nav {
display: flex;
justify-content: space-between; /* main axis */
align-items: center; /* cross axis */
gap: 1rem;
}

Grid (two dimensions)​

.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}

Responsive design​

.sidebar { display: none; }

@media (min-width: 768px) {
.sidebar { display: block; width: 240px; }
}

Design mobile first: base styles for small screens, then enhance with min-width media queries. Use relative units (rem, %, vw) and CSS variables:

:root { --brand: #2563eb; }
.button { background: var(--brand); }