In this recipe you will see how to center one box inside another. Centering both horizontally and vertically was difficult before flexbox, with the Box Alignment properties it is now straightforward.
To place an item into the center of another box horizontally and vertically.
To center one box inside another we make the containing box a flex container. Then set
align-items
to center to perform centering on the block axis, and
justify-content
to center to perform centering on the inline axis.
In the future we may be able to center elements without needing to turn the parent into a flex container, as the Box Alignment properties used here are specified to apply to block layout too. However, support is currently limited for box alignment properties on block layout, so currently centering using Flexbox is the most robust way to achieve this.
The various layout methods have different browser support. See the charts below for details on basic support for the properties used.
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Supported in Flex Layout |
Chrome
完整支持
52
|
Edge 完整支持 12 |
Firefox
完整支持
20
注意事项
|
IE
完整支持
11
注意事项
|
Opera 完整支持 12.1 | Safari 完整支持 9 |
WebView Android
完整支持
52
|
Chrome Android
完整支持
52
|
Firefox Android
完整支持
20
注意事项
|
Opera Android 完整支持 12.1 | Safari iOS 完整支持 9 |
Samsung Internet Android
完整支持
6.0
|
| Supported in Grid Layout | Chrome 完整支持 57 | Edge 完整支持 16 | Firefox 完整支持 52 | IE 不支持 No | Opera 完整支持 44 | Safari 完整支持 10.1 | WebView Android 完整支持 57 | Chrome Android 完整支持 52 | Firefox Android 完整支持 52 | Opera Android 完整支持 43 | Safari iOS 完整支持 10.3 | Samsung Internet Android 完整支持 6.2 |
完整支持
不支持
见实现注意事项。
用户必须明确启用此特征。
要求使用供应商前缀或不同名称。
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Supported in Flex Layout |
Chrome
完整支持
52
|
Edge 完整支持 12 |
Firefox
完整支持
20
注意事项
|
IE 完整支持 11 | Opera 完整支持 12.1 | Safari 完整支持 9 |
WebView Android
完整支持
52
|
Chrome Android
完整支持
52
|
Firefox Android
完整支持
20
注意事项
|
Opera Android 完整支持 12.1 | Safari iOS 完整支持 9 |
Samsung Internet Android
完整支持
6.0
|
| Supported in Grid Layout | Chrome 完整支持 57 | Edge 完整支持 16 | Firefox 完整支持 52 | IE 不支持 No | Opera 完整支持 44 | Safari 完整支持 10.1 | WebView Android 完整支持 57 | Chrome Android 完整支持 52 | Firefox Android 完整支持 52 | Opera Android 完整支持 43 | Safari iOS 完整支持 10.3 | Samsung Internet Android 完整支持 6.2 |
完整支持
不支持
见实现注意事项。
用户必须明确启用此特征。
要求使用供应商前缀或不同名称。