Center div

2 snippets in HTML & CSS

HCHTML & CSS

Center Anything with Flexbox

HC · Flexbox
Syntax
display: flex;
justify-content: center;
align-items: center;
Example
/* Center a single element both horizontally and vertically */
.page-center {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

/* Shorter alternative using place properties */
.quick-center {
  display: flex;
  place-content: center;
  place-items: center;
}

Note This three-line pattern is the simplest way to center anything vertically and horizontally. Add min-height: 100vh to center within the full viewport.

Centering Methods Summary

HC · Layout & Positioning
Syntax
/* Horizontal block centering */
margin: 0 auto;
/* Flex centering */
display: flex; justify-content: center; align-items: center;
/* Grid centering */
display: grid; place-items: center;
/* Absolute centering */
position: absolute; inset: 0; margin: auto;
Example
/* Method 1: margin auto (horizontal only) */
.container { margin: 0 auto; max-width: 800px; }

/* Method 2: flexbox (both axes) */
.flex-center { display: flex; justify-content: center; align-items: center; }

/* Method 3: grid (both axes, shortest) */
.grid-center { display: grid; place-items: center; }

/* Method 4: absolute (both axes, within parent) */
.abs-center { position: absolute; inset: 0; margin: auto; width: fit-content; height: fit-content; }

Note For most cases, the grid place-items: center approach is the shortest and most versatile. Use margin auto for simple block-level horizontal centering. The absolute method works when you need to center within a positioned parent.

Frequently asked questions

How do you center div?
HTML & CSS covers this with 2 copy-ready snippets on this page. The "Center Anything with Flexbox" snippet in HTML & CSS uses `display: flex;`.
Which code does the HTML & CSS example use?
The "Center Anything with Flexbox" snippet uses `display: flex;`, from the Flexbox section of the HTML & CSS cheat sheet.
What other HTML & CSS snippets are shown for "center div"?
Besides "Center Anything with Flexbox", this page also shows "Centering Methods Summary".
Is there anything to watch out for?
Yes. For "Center Anything with Flexbox": This three-line pattern is the simplest way to center anything vertically and horizontally. Add min-height: 100vh to center within the full viewport.