margin: top right bottom left;margin: vertical horizontal;margin: all;
Example
.section{margin:40px0;}.container{margin:0 auto;/* center horizontally */max-width:1200px;}.spaced-item{margin-top:16px;margin-bottom:16px;}
Note Vertical margins collapse: when two vertical margins touch, only the larger one applies (not their sum). Margins on flex and grid children do not collapse. Use margin: 0 auto on a block element with a set width to center it.
/* 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.
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 element?
HTML & CSS covers this with 3 copy-ready snippets on this page. The "Margin" snippet in HTML & CSS uses `margin: top right bottom left;`.
Which code does the HTML & CSS example use?
The "Margin" snippet uses `margin: top right bottom left;`, from the Box Model section of the HTML & CSS cheat sheet.
What other HTML & CSS snippets are shown for "center element"?
Besides "Margin", this page also shows "Center Anything with Flexbox", "Centering Methods Summary".
Is there anything to watch out for?
Yes. For "Margin": Vertical margins collapse: when two vertical margins touch, only the larger one applies (not their sum). Margins on flex and grid children do not collapse. Use margin: 0 auto on a block element with a set width to center it.