首页 > web前端 > css教程 > 正文

如何在CSS Grid中居中?

王林
发布: 2023-08-22 23:13:01
转载
2489人浏览过

网格以行和列布局的形式排列内容。css网格也是如此。

在CSS Grid中使用Flex进行居中

将网格项设置为弹性容器−

display: flex
登录后复制

要垂直和水平居中,使用−

align-items: center;
justify-content: center;
登录后复制

示例

让我们来看一个完整的例子 −

<!DOCTYPE html>
<html>
<head>
   <title>Grid and Flex Example</title>
   <style>
      html,body {
         margin: 0;
         padding: 0;
      }

      .box {
         display: grid;
         grid-template-columns: 1fr 1fr;
         grid-template-rows: 100vh;
      }

      .first,
      .second {
         display: flex;
         align-items: center;
         justify-content: center;
      }

      .first {
         background-color: orange;
      }

      .second {
         background-color: yellow;
      }
   </style>
</head>
<body>
   <div class="box">
      <div class="first">Left</div>
      <div class="second">Right</div>
   </div>
</body>
</html>
登录后复制

输出

如何在CSS Grid中居中?

使用CSS Grid实现居中,无需使用Flex

我们也可以不使用Flex来居中。我们将网格容器设置为display: grid。当display属性设置为grid时,HTML元素将成为网格容器 -

百度文心百中
百度文心百中

百度大模型语义搜索体验中心

百度文心百中 22
查看详情 百度文心百中

立即学习前端免费学习笔记(深入)”;

grid-container {
   display: grid;
   grid-template-columns: 1fr 1fr;
   grid-auto-rows: 150px;
   grid-gap: 20px;
}
登录后复制

网格项目使用相对定位设置 -

grid-item {
   position: relative;
   text-align: center;
}
登录后复制

示例

然而,

<!DOCTYPE html>
<html>
<head>
   <title>Grid</title>
   <style>
      grid-container {
         display: grid;
         grid-template-columns: 1fr 1fr;
         grid-auto-rows: 150px;
         grid-gap: 20px;
      }

      grid-item {
         position: relative;
         text-align: center;
      }

      grid-container {
         background-color: red;
         padding: 10px;
      }

      grid-item {
         background-color: orange;
      }
   </style>
</head>
<body>
   <grid-container>
      <grid-item>This is in the center</grid-item>
      <grid-item>This is in the center</grid-item>
   </grid-container>
</body>
</html>
登录后复制

输出

如何在CSS Grid中居中?

以上就是如何在CSS Grid中居中?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号