网页 综合 更新时间 2025-11-07 15:58:06

Center an element - CSS | MDN

自动蜘蛛 developer.mozilla.org 正文约 1766 字
HTML: Markup language
CSS: Styling language
JavaScript: Scripting language
Web APIs: Programming interfaces
Learn web development
Get to know MDN better
In this recipe, you will see how to center one box inside another by using flexbox and grid, centering content both horizontally and vertically.
To place an item into the center of another box horizontally and vertically.
Click "Play" in the code blocks below to edit the example in the MDN Playground:
To center a box within another box, first turn the containing box into a flex container by setting its display property to flex. Then set align-items to center for vertical centering (on the block axis) and justify-content to center for horizontal centering (on the inline axis). And that's all it takes to center one box inside another!
We set a height for the container to demonstrate that the inner item is indeed vertically centered within the container.
Instead of applying align-items: center; on the container, you can also vertically center the inner item by setting align-self to center on the inner item itself.
Another method you can use for centering one box inside another is to first make the containing box a grid container and then set its place-items property to center to center align its items on both the block and inline axes.
Instead of applying place-items: center; on the container, you can achieve the same centering by setting place-content: center; on the container or by applying either place-self: center or margin: auto; on the inner item itself.
This page was last modified on Nov 7, 2025 by MDN contributors.
Your blueprint for a better internet.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.
访问原文 返回搜索 https://developer.mozilla.org/en-US/docs/Web/CSS/How_to/Layout_cookbook/Center_an_element
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。