五种用于水平和垂直居中的CSS网格方法
>本文探讨了五种CSS网格技术,用于水平和垂直方向居中。 这些方法适用于任何HTML元素。 我们还将简要介绍Flexbox和基于转换的中心,这些中心已在其他地方介绍。钥匙要点:
> CSS网格提供了五种有效的方法来集中A Div:
place-self
place-items
中心单个网格项目,使其他项目可以自由定位。它结合了place-content
(水平)和place-self
>适用于网格容器,当所有项目需要相同的放置时,理想。 这是justify-self
和align-self
>的速记。place-items
>将整个网格容器的内容对齐,将所有项目视为单个组。它结合了justify-items
和align-items
>。place-content
justify-content
align-content
和初始CSS:
<article> <div></div> </article>
所有示例都使用
article { width: 100%; min-height: 100vh; background: black; display: grid; } div { width: 200px; background: yellow; height: 100px; }
元素作为网格容器建立。 该容器被制成宽且高的容器以提供足够的空间。
居中方法:display: grid
article
:这很容易将网格项目集中在其单元格中。
place-self
article { display: grid; } div { place-self: center; }
:place-self
这将其中心的所有网格项目集中在其细胞中。justify-self
align-self
place-items
是和article { display: grid; place-items: center; }
place-content
:这将整个网格内容作为组中心。<article> <div></div> </article>
[codepen演示:带有CSS网格和位置含量的元素](链接到codepen)
place-content
是justify-content
和space-around
的值作为space-evenly
>的替代方案。center
>
article { width: 100%; min-height: 100vh; background: black; display: grid; } div { width: 200px; background: yellow; height: 100px; }
这种简单的技术使浏览器可以处理间距。
article { display: grid; } div { place-self: center; }
或者,使用命名的网格区域:
[Codepen演示:使用命名区域的CSS网格中心A DIV]
article { display: grid; place-items: center; }
所有方法有效地居中。对于直接元素定位,
>和自动边距很方便。 选择最适合您的布局复杂性和需求的方法。 请记住,这些技术在除divs以外的元素上起作用。 这些示例使用一个空的div,但添加内容维护中心。>
(FAQS部分在很大程度上重复了,并且该问题答案已经在文章中隐含地介绍了。)以上是如何使用CSS网格中心的详细内容。更多信息请关注PHP中文网其他相关文章!