Choose the right centering method for text, images and boxes using margins, Flexbox or Grid.
Centering works when you identify what should move and which box provides its available space. A line of text inside a card, the card inside its wrapper, and the wrapper inside the page are three different alignment problems. This guide starts with those distinctions and gives you a complete example to experiment with. You will learn when to use text alignment, auto margins, Flexbox, and Grid, and how to see why a layout appears off centre even when a centering declaration is present.
Decide what should move
If a paragraph has a full-width box and you want the text on each line to sit in the middle, use the text alignment property on the paragraph or a suitable ancestor. This changes how inline content fits inside its line boxes. It does not move the paragraph’s border box. Give the paragraph an outline during a test and you can see the difference: the outline stays where it was, while the letters shift.
If you want a narrower block in the middle of its parent, give it an appropriate width or maximum width and allow its inline margins to share the remaining space. If the box already fills the width, the margins have no extra room to share and there is nothing to move. Avoid applying a fixed width larger than a narrow phone’s viewport. A capped width that can shrink with the parent gives you a visible effect without creating horizontal scrolling.
Vertical centering needs available space as well. A container that fits its child exactly cannot display vertical movement. Define the minimum height when the blank area is part of the design. For a page section that grows with content, prefer a minimum over a fixed height. That lets the section expand if the text is long or the visitor increases their font size. A fixed height may look centred with the sample content and then cut off a translated title.
Try all four approaches in one page
Paste the example into the HTML editor. Each block highlights the space used for alignment. Remove individual declarations and re-run the example to see which change affects each box.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSS centering practice</title>
<style>
* { box-sizing: border-box; }
body { max-width: 46rem; margin: 2rem auto; padding-inline: 1rem; font: 1rem/1.5 system-ui; color: #10244a; }
.area { margin-block: 1rem; padding: .75rem; background: #e5f3ff; border-radius: .6rem; }
.text { text-align: center; }
.block { width: min(100%, 15rem); margin-inline: auto; background: #daefd4; padding: .6rem; }
.flex { display: flex; justify-content: center; align-items: center; min-height: 10rem; }
.grid { display: grid; place-items: center; min-height: 10rem; }
.sample { background: #daefd4; padding: .6rem; max-width: 100%; }
</style>
</head>
<body>
<main>
<h1>Four centering techniques</h1>
<section><h2>Text within its line</h2><p class="area text">This text sits in the middle of its line.</p></section>
<section><h2>A block within its parent</h2><div class="area"><p class="block">The block moves. Its text keeps start alignment.</p></div></section>
<section><h2>A Flexbox item on two axes</h2><div class="area flex"><div class="sample">Flexbox sample</div></div></section>
<section><h2>A Grid item on two axes</h2><div class="area grid"><div class="sample">Grid sample</div></div></section>
</main>
</body>
</html>
Try it in the HTML editor
In the block example, those two auto margins share the horizontal space on either side. The text remains start-aligned because you are positioning the outside of the paragraph, not changing the lines inside it. Logical inline margins work with different writing directions. In an ordinary horizontal writing mode they control the left and right spaces. If you switch the document to a vertical writing mode, an inline dimension follows that mode instead of always meaning physical width.
Align a flex item or a grid item
In the Flexbox example, the container is the blue area and the item is the green sample. The main axis follows the chosen flex direction. With a row direction, the main axis usually runs across the page and the cross axis runs down it. Justify content handles the distribution on the main axis while align items handles the cross axis. Change the direction to column and watch which declaration controls each direction. A rule that looked like horizontal centering before may now be working vertically.
The Grid example uses a shorthand to set item alignment in its area on both axes. This is convenient for a single badge inside an empty panel. With multiple grid cells, the same declaration aligns each item within its own grid area. It does not necessarily centre the complete grid of tracks inside the container. If the items look centred in their cells but a narrow set of tracks still hugs one side, inspect track sizing and grid content alignment separately. The CSS Grid Generator is a useful place to experiment with track counts once it is available on the site.
Center an image without stretching it
An image is inline by default, so centering the text in its parent can centre the image’s inline box as well. Use that when the image participates in a line of text. If the image is a standalone block, set it to block display and apply auto inline margins instead. Leave its height automatic and cap its width to the available space. If you explicitly make it fill the whole width there is no remaining space to show the auto margins, even though the sizing still works.
A visible gap below an inline image can come from baseline alignment rather than the centering rule. Inline content normally leaves room for letters that descend below the baseline. If the image represents a figure on its own, block display can remove that baseline gap. If it is an icon beside text, adjust its vertical alignment in the line instead. Compare the icon at the font sizes your design actually uses before choosing that adjustment.
Debug the box before tweaking the value
Open the inspector and identify the selected element and its parent. What is their width and height? Is the alignment property on the element that owns the layout? Margin centering needs room outside the box. Grid and Flexbox need a correctly configured container. If a child is centred but the visible contents still look uneven, check padding, an overflowing line, or unequal shapes inside the box. Mechanical centering positions boxes. A logo with transparent padding on one side can still look visually offset.
Finish by changing the sample to a short line, then a long line, then a two-line block. Try each at phone width and at a desktop width. If the layout still works after text grows, copy the relevant rule into the CSS editor and adapt it to your project. For more examples, see MDN’s centering recipe.
Keep a centered item usable when its content grows
A centered panel can look wrong if its contents overflow. This often appears in small modal designs: a short message fits beautifully, but an error explanation extends above or below the visible area. Start by letting the panel’s content determine its height. Set a practical maximum width and use padding to preserve breathing room. If the outer container must fill the screen, let it scroll rather than trapping parts of a tall panel outside the viewport. Adjust alignment based on the needs of the layout, such as switching to start alignment when an item cannot safely fit in the middle.
Test the flex example with substantially longer text. Then repeat the test with a very long unbroken string. The results are different because normal text can wrap at a space, while an unbroken string may introduce horizontal overflow. A sensible overflow wrapping rule can help where breaking the string is acceptable. If the string is a code sample or identifier whose formatting matters, a contained scroll area may be a better choice. Centering declarations cannot resolve those content decisions by themselves.
Choose one method and remove competing rules
If you inherit a layout that combines absolute positioning, a transform, and several alignment properties, return to the smallest example that still demonstrates the problem. Temporarily outline the container and the child in different colours. Turn off one rule at a time and note what changes. Absolute positioning may have taken the item out of normal flow, so adding auto margins to it may not act like the block example. A translation may still move it after a flex container has already positioned it. Removing the conflicting rule is often more reliable than adding another correction.
Use the method that expresses the layout you intend. For a block that should remain in ordinary flow, auto margins are easy to read. For an item sharing a layout with nearby controls, use the alignment tools of that layout. Keep the final selectors close to the container they control so a future change to a parallel section does not accidentally shift this one.