如何将项目居中

在本指南中,你可以了解如何将项目在另一个元素内水平和垂直居中。

¥In this guide you can find out how to center an item inside another element, both horizontally and vertically.

居中放置一个盒子

¥Center a box

要使用 CSS 将一个框置于另一个框的中心,你需要在父容器上使用 CSS 框对齐 属性。由于这些对齐属性尚不具备对块和内联布局的浏览器支持,因此你需要将父级设置为 flexgrid 容器才能启用使用对齐的功能。

¥To center one box inside another using CSS you will need to use CSS box alignment properties on the parent container. As these alignment properties do not yet have browser support for block and inline layout you will need to make the parent a flex or grid container to turn on the ability to use alignment.

在下面的示例中,我们给出了父容器 display: flex;然后将 justify-content 设置为居中以水平对齐,将 align-items 设置为居中以垂直对齐。

¥In the example below we have given the parent container display: flex; then set justify-content to center to align it horizontally, and align-items to center to align it vertically.

注意:你可以使用此技术对一个或多个元素在另一个元素中进行任何类型的对齐。在上面的示例中,你可以尝试将 justify-contentalign-items 的值更改为任何有效值。

¥Note: You can use this technique to do any kind of alignment of one or more elements inside another. In the example above you can try changing the values to any valid values for justify-content and align-items.

也可以看看