CSS Border Cheat Sheet: Selectors and Properties

css css-border selectors web-development css-properties

CSS border declarations, selectors, and the box model are the building blocks of every stylesheet you write. This cheat sheet gathers the properties you reach for most often — from border syntax and selector patterns to colors, typography, flexbox shorthand, and pseudo-classes — so you can stay in your editor instead of hunting through docs.

CSS Border Properties

The border shorthand combines width, style, and color in a single declaration. Each side can also be targeted individually when you need to override just one edge, and border-radius rounds corners without affecting the layout of surrounding elements.

PropertyValuesExample
borderwidth style colorborder: 1px solid #ccc
border-widthpx, em, thin, medium, thickborder-width: 2px
border-stylesolid, dashed, dotted, double, groove, ridge, noneborder-style: dashed
border-colorAny color valueborder-color: #333
border-radiusLength, %border-radius: 8px
border-topShorthand for one sideborder-top: 2px dashed red
border-rightShorthand for one sideborder-right: none
border-bottomShorthand for one sideborder-bottom: 1px solid #e2e8f0
border-leftShorthand for one sideborder-left: 4px solid #3b82f6
outlinewidth style coloroutline: 2px solid blue
box-shadowx y blur spread colorbox-shadow: 0 2px 4px rgba(0,0,0,.15)
/* Card with rounded border */
.card {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 24px;
}

/* Accent left border — sidebar callout pattern */
.callout {
  border: none;
  border-left: 4px solid #3b82f6;
  padding-left: 16px;
  background-color: #eff6ff;
}

/* Circle via border-radius */
.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  border: 2px solid #6366f1;
}

/* Focus ring — does not shift layout */
button:focus-visible {
  outline: 2px solid #3b82f6;
  outline-offset: 2px;
}

outline differs from border in one key way: it does not participate in the box model and never shifts surrounding elements. Use outline for focus rings, where visible feedback is needed without layout side effects. Use border when the visual boundary should contribute to the element’s total size and spacing.

For the full MDN spec on every border sub-property, see the MDN CSS border reference.


CSS Selectors Reference

Selectors determine which elements a rule applies to. Element, class, and ID selectors cover the majority of cases; attribute selectors and combinators handle the rest. Specificity — the scoring system CSS uses when two rules conflict — is the most common source of “why isn’t this applying?” bugs.

SelectorMatchesExample
elementTag by namep { }
.classElements with class.card { }
#idElement with ID#nav { }
*All elements* { box-sizing: border-box }
A BB anywhere inside Anav a { }
A > BB direct child of Aul > li { }
A + BB immediately after Ah2 + p { }
A ~ BAll B siblings after Ah2 ~ p { }
[attr]Has attributeinput[required] { }
[attr="val"]Exact attribute matchinput[type="text"] { }
[attr^="val"]Attribute starts with valuea[href^="https"] { }
[attr$="val"]Attribute ends with valuea[href$=".pdf"] { }
[attr*="val"]Attribute contains valuea[href*="devnook"] { }
/* Descendant vs direct child */
.menu a { color: inherit; }       /* any link inside .menu */
.menu > li { list-style: none; }  /* only top-level list items */

/* Attribute selectors */
input[type="email"] {
  border: 1px solid #94a3b8;
  padding: 8px 12px;
}

/* External link indicator */
a[href^="https"]::after {
  content: " ↗";
  font-size: 0.75em;
  opacity: 0.6;
}

/* Any element carrying a tooltip */
[data-tooltip] {
  position: relative;
  cursor: help;
  text-decoration: underline dotted;
}

Specificity scores: inline styles (1-0-0-0) > ID (0-1-0-0) > class, attribute, pseudo-class (0-0-1-0) > element, pseudo-element (0-0-0-1). When a rule isn’t applying, compare the specificity scores of both competing selectors — the higher score wins regardless of source order.


Box Model: Spacing and Sizing

Every element in CSS occupies a rectangular box. The box model defines four layers: content, padding, border, and margin. Setting box-sizing: border-box globally makes width and height include padding and border — the behavior most developers expect and the reason every modern reset starts with it.

PropertyValuesNotes
box-sizingcontent-box, border-boxUse border-box globally
marginLength, auto, %, 0Shorthand: top right bottom left
paddingLength, %, 0Same shorthand order as margin
widthLength, %, auto, min-content, max-content, fit-content
heightLength, %, auto, min-content
max-widthLength, %, noneCommon: 1200px or 90rem for page wrapper
min-heightLength, %, 0
overflowvisible, hidden, scroll, auto, clip
displayblock, inline, inline-block, flex, grid, none
positionstatic, relative, absolute, fixed, sticky
z-indexInteger, autoOnly applies to positioned elements
/* Global reset — include in every project */
*, *::before, *::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* Centered page wrapper */
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

/* Shorthand: top | right | bottom | left */
.section {
  padding: 48px 24px;    /* 48px top/bottom, 24px left/right */
  margin-bottom: 32px;
}

/* Sticky header */
.header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #fff;
  border-bottom: 1px solid #e2e8f0;
}

margin: 0 auto on a block element with a defined width horizontally centers it — this pattern appears on almost every layout wrapper. Vertical centering with auto does not work the same way; reach for flexbox align-items: center or grid place-items: center instead.


Colors, Backgrounds and Typography

CSS accepts five color formats: hex, rgb(), rgba(), hsl(), and named keywords. For design-system work, hsl() makes it straightforward to derive tints and shades from a base hue. For overlays and transparency, rgba() is the standard choice.

PropertyValuesNotes
colorHex, rgb, hsl, keywordText and foreground color
background-colorAny color valueFill color only
backgroundColor, image, gradientShorthand — covers all background sub-properties
opacity01Affects entire element and its children
font-familyFont name or stackAlways include a generic fallback
font-sizerem, em, px, %, vwPrefer rem for accessibility
font-weight100900, bold, normal
font-stylenormal, italic, oblique
line-heightUnitless number, length1.51.7 for readable body copy
letter-spacingLength, normalCan be negative for tight headings
text-alignleft, center, right, justify
text-decorationnone, underline, line-through
text-transformuppercase, lowercase, capitalize, none
white-spacenormal, nowrap, pre, pre-wrapUse nowrap for truncation patterns
:root {
  font-size: 16px;
}

.heading-lg {
  font-size: 2rem;           /* 32px relative to root */
  font-weight: 700;
  line-height: 1.2;
  letter-spacing: -0.025em;
  color: #1a202c;
}

.body-text {
  font-size: 1rem;
  line-height: 1.7;
  color: #4a5568;
}

/* Gradient background */
.hero {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
}

/* Semi-transparent overlay */
.overlay {
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}

Use rem units for font-size — it respects user browser zoom preferences and accessibility settings. em works better for padding and margin on components where spacing should scale proportionally with the local font size, such as button padding.


Flexbox Layout Quick Reference

Flexbox handles one-dimensional layouts — rows or columns. It is the standard tool for navigation bars, card rows, and any pattern that distributes items along a single axis. For a complete property-by-property reference, see the CSS Flexbox cheatsheet.

PropertyValuesNotes
display: flexCreates flex container
flex-directionrow, column, row-reverse, column-reverseDefault is row
justify-contentflex-start, flex-end, center, space-between, space-around, space-evenlyMain axis distribution
align-itemsstretch, flex-start, flex-end, center, baselineCross axis alignment
flex-wrapnowrap, wrap, wrap-reverseDefault is nowrap
gapLengthSpace between items — replaces old margin hacks
flex-growNumberHow much the item grows to fill remaining space
flex-shrinkNumberHow much the item shrinks when space is tight
flex-basisLength, auto, contentStarting size before grow/shrink calculation
flexgrow shrink basisShorthand — flex: 1 equals 1 1 0%
align-selfSame as align-itemsPer-item override of container alignment
orderIntegerVisual reorder without changing DOM (default 0)
/* Horizontal navigation bar */
.nav-list {
  display: flex;
  align-items: center;
  gap: 8px;
  list-style: none;
  margin: 0;
  padding: 0;
}

/* Responsive card row that wraps */
.card-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}

.card-grid > .card {
  flex: 1 1 300px;  /* grow, shrink, minimum width 300px */
}

/* Full-viewport hero with centered content */
.hero-content {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 16px;
  min-height: 100vh;
}

Flexbox is one-dimensional — it handles a row or a column at a time. When a layout needs to span rows and columns simultaneously, CSS Grid is the better fit. For a side-by-side breakdown of when each layout model makes sense, the CSS flexbox vs grid comparison covers the decision points clearly.


Pseudo-classes and Pseudo-elements

Pseudo-classes target elements based on state or position in the DOM tree. Pseudo-elements style a specific part of an element or inject generated content. The distinction matters: pseudo-classes use a single colon (:hover), pseudo-elements use a double colon (::before).

SelectorMatchesCommon Use
:hoverMouse over elementLink colors, button lift effects
:focusElement has focusFocus rings
:focus-visibleFocus from keyboard onlyAccessible ring without mouse hover
:activeBeing clicked right nowButton press state
:visitedPreviously clicked linkLink history differentiation
:disabledDisabled form controlDimmed input fields
:checkedChecked checkbox or radioCustom toggle component styles
:first-childFirst sibling in parentList start, remove top margin
:last-childLast sibling in parentRemove last border or margin
:nth-child(n)Nth siblingZebra-striped table rows
:nth-child(even)Even siblingsAlternating row backgrounds
:not(selector)Elements NOT matching selectorExclude specific items
:emptyNo children or text contentHide empty containers
::beforeGenerated content before elementBadges, quote marks, icons
::afterGenerated content after elementClearfix hack, closing punctuation
::placeholderInput placeholder textPlaceholder color and style
::selectionUser-selected textCustom highlight color
::first-lineFirst rendered line of block textDrop caps, special callouts
/* Keyboard-only focus ring */
button:focus-visible {
  outline: 2px solid #3b82f6;
  outline-offset: 2px;
}

/* Zebra-striped table */
tbody tr:nth-child(even) {
  background-color: #f8fafc;
}

/* Remove last item's bottom border */
.list-item:last-child {
  border-bottom: none;
}

/* Opening quote mark via pseudo-element */
blockquote::before {
  content: '\201C';    /* Unicode left double quotation mark */
  font-size: 3rem;
  line-height: 0;
  vertical-align: -0.4em;
  color: #94a3b8;
}

/* Style sibling label when checkbox is checked */
input[type="checkbox"]:checked + label {
  font-weight: 600;
  color: #3b82f6;
  text-decoration: line-through;
}

:focus-visible is the modern answer to the old :focus { outline: none } anti-pattern. It keeps the focus ring for keyboard navigation while suppressing it for mouse clicks — the behavior most products need without the accessibility regression. Browser support is broad enough to use today without a fallback.


Conclusion

CSS border properties, selectors, and layout rules appear in every project — a single-page reference like this one removes the friction of constant lookups. Once your stylesheet is working, the CSS minification and performance guide covers how to reduce delivery time without changing any visual behavior. For the full property list including browser compatibility tables, the MDN CSS Reference remains the most reliable source for edge-case syntax and spec-accurate definitions.