Choose a centering technique based on what you are centering. A block box, text inside a box, and a flex or grid item have different alignment rules.
Working example
HTML and CSS
HTML
<article>This block stays centered as the preview narrows.</article>
CSS
article {
width: 85%;
max-width: 28rem;
margin-inline: auto;
padding: 1rem;
background: #dbeafe;
}
Edit HTML or CSS to update the preview as you type. Copy code snippet copies the selected tab. Preview spacing and font defaults are not included.
HTML and CSS
HTML
<nav aria-label="Example topics"><a href="#topic">Read the topic</a></nav>
<h2 id="topic">Topic</h2>
CSS
nav {
text-align: center;
}
a {
display: inline-block;
padding: 0.7rem;
}
Edit HTML or CSS to update the preview as you type. Copy code snippet copies the selected tab. Preview spacing and font defaults are not included.
HTML and CSS
HTML
<div class="frame">
<p class="note">Grid aligns this item within its area.</p>
</div>
CSS
.frame {
display: grid;
justify-items: center;
background: #eff6ff;
padding: 1rem;
}
.note {
max-width: 20rem;
padding: 1rem;
border: 1px solid #2563eb;
}
Edit HTML or CSS to update the preview as you type. Copy code snippet copies the selected tab. Preview spacing and font defaults are not included.
Why these techniques differ
Auto inline margins share the available space beside the block. It needs room on either side; a full-width block has none. A responsive percentage or max-width works, so a fixed pixel width is not required.
text-align aligns inline content inside the parent. It does not center an ordinary block’s own box. Grid’s justify-items aligns items on the inline axis. In a row flex container, justify-content distributes items along the main axis; changing flex-direction changes that axis.
Positioning is a different constraint
left: 50% uses the containing block’s width; translateX(-50%) uses the transformed element’s own reference box. That combination can center an absolutely positioned overlay, but it removes it from normal flow. Prefer normal layout for article and form content.
Sources
Reference 1 Reference 2 Reference 3 Reference 4 provide the technical details and current compatibility information.