掌握居中网格布局

CSSCSSBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索使用 CSS 进行网格居中的概念。你将学习如何使用 grid 布局在父元素内水平和垂直居中一个子元素。在本实验结束时,你将对如何使用 justify-contentalign-items 属性来创建完美居中的布局有深入的理解。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL css(("CSS")) -.-> css/BasicConceptsGroup(["Basic Concepts"]) css(("CSS")) -.-> css/CoreLayoutGroup(["Core Layout"]) css/BasicConceptsGroup -.-> css/selectors("Selectors") css/CoreLayoutGroup -.-> css/width_and_height("Width and Height") css/CoreLayoutGroup -.-> css/display_property("Display Property") subgraph Lab Skills css/selectors -.-> lab-35205{{"掌握居中网格布局"}} css/width_and_height -.-> lab-35205{{"掌握居中网格布局"}} css/display_property -.-> lab-35205{{"掌握居中网格布局"}} end

网格居中

虚拟机中已经提供了 index.htmlstyle.css

要在父元素内将子元素水平和垂直居中,请执行以下步骤:

  1. 使用 display: grid 创建网格布局。
  2. 使用 justify-content: center 将子元素水平居中。
  3. 使用 align-items: center 将子元素垂直居中。

以下是一个示例 HTML 结构:

<div class="parent">
  <div class="child">Centered content.</div>
</div>

以及相应的 CSS:

.parent {
  display: grid;
  justify-content: center;
  align-items: center;
  height: 100px;
}

请点击右下角的“Go Live”以在端口 8080 上运行 Web 服务。然后,你可以刷新“Web 8080”标签页来预览网页。

总结

恭喜你!你已经完成了网格居中实验。你可以在 LabEx 中练习更多实验来提升你的技能。