如何使用flex / grid将网格在容器中居中?

如何解决如何使用flex / grid将网格在容器中居中?

即使对div居中存在很多问题,哪些问题不可行,出于某种原因,它们似乎都不起作用。作为我使用flex / grid的CSS菜鸟,我所知道的就是我想要拥有:

  • 固定标头
  • 固定的中间内容(水平和垂直居中)
  • 固定页脚

    <div className="flex flex-col h-screen">
      <!-- HEADER -->
      <header className="flex h-20 bg-gray-100 justify-center items-center">
        <span className="font-bold text-2xl">
          title
        </span>
      </header>
    
      <!-- BODY -->
      <div className="flex-1 flex-col mx-auto justify-center items-center max-w-screen-lge p-5">
        <div className="grid grid-cols-2 gap-4 items-center">
          <div className="flex col-span-1 h-20 items-center justify-center bg-gray-300">
            1
          </div>
          <div className="flex col-span-1 h-20 justify-end bg-gray-300">
            2
          </div>
          <div className="flex col-span-2 h-12 items-center justify-center bg-gray-300">
           3
          </div>
          <div className="flex col-span-2 h-48 items-center justify-center bg-gray-300">
            4
          </div>
          <div className="flex col-span-2 h-48 items-center justify-center bg-gray-300">
            5
          </div>
        </div>
      </div>
    
      <!-- FOOTER -->
      <footer className="flex h-20 bg-gray-100 justify-center items-center">
        <p>footer text</p>  
      </footer>
    </div>

到目前为止,它看起来像这样: layout

我如何将div居中于flex-1容器内(这是一个正确的选择吗?)?

编辑: parent element content (child)

解决方法

不确定如何在顺风中做到这一点,但这是一个简单的示例,说明如何使用普通CSS做到这一点。

我没有以任何结构性方式更改您的标记。只是删除了类名,以便更轻松地了解什么正在影响什么。

这在微小的堆栈溢出摘要窗口中以一种不希望的方式压扁了(您可能想考虑一下),因此您应该扩展它以查看发生了什么。

垂直居中的关键是.content上的flex设置,它包装了网格布局:

  • 通过display: flex使其成为Flex容器
  • 确保该高度与您要居中的区域一样高,可通过min-height: 100vh在此处完成
  • 设置flex-direction: column,使其项垂直堆叠。 (您可以不这样做而这样做,但这对我来说更有意义。)
  • 设置justify-content: center以使内容居中。它垂直居中,因为这是弯曲方向轴。

您也可以通过place-items和flex或grid的某种组合来到达那里。

html,body,p {
  margin: 0;
  padding: 0;
}

.header {
  position: fixed; /* don't move,no matter what */
  top: 0; /* position fixed removes it from the normal laytou flow,so we should tell it where to be */
  left: 0;
  right: 0;
  width: 100vw;
  background: lightskyblue;
  text-align: center;
}

.footer {
  /*
  same as .header above but pinned to bottom instead of top.
  you could reduce repetition by putting the common rules in their
  own class (.fixed or whatever) and then have a secondary class for
  .top or .bottom,but this is fine for the purposes of this demo.
  */
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100vw;
  background: lightskyblue;
  text-align: center;
}

.content {
  min-height: 100vh; /* as tall as the viewport because that's where we want to be centered */
  max-width: 80vw; /* limit width */
  margin: 0 auto; /* center horizontally */

  display: flex; /* vertical centering is easy with flex */
  flex-direction: column;
  justify-content: center; /* see? */
  
  /*
  you could also accomplish the vertical centering with
  flex-direction: row (the default) and align-items: center
  instead of justify-content,but this way makes more sense to
  me for whatever reason
  */
}

.content-grid {
  display: grid; /* establish the grid container */
  grid-template-columns: repeat(2,50%); /* for this we only need 2 equal columns */
  grid-template-rows: 70px 50px 100px 100px; /* just ballpark/eyeballed row heights to make it vaguely resemble your example image */
  gap: 1rem; /* space between the blocks */
}

.content-grid > * {
  background: aliceblue; /* just so you can see it */
}

.content-grid > :nth-child(n + 3) { /* 1n + 3 translates as 'every one-th item starting at item 3' */
  /*
  make every block after the first two occupy the entire row.
  start at gridline 1,end at the last one (aka -1)
  */
  grid-column: 1 / -1; 
}
<div>
  <!-- HEADER -->
  <header class="header">
    <span>
      title
    </span>
  </header>

  <!-- BODY -->
  <div class="content">
    <div class="content-grid">
      <div>
        1
      </div>
      <div>
        2
      </div>
      <div>
       3
      </div>
      <div>
        4
      </div>
      <div>
        5
      </div>
    </div>
  </div>

  <!-- FOOTER -->
  <footer class="footer">
    <p>footer text</p>  
  </footer>
</div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-