You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Materialize CSS在大屏及移动端居中指定div元素?

搞定Materialize CSS中root容器全端居中的问题

嘿,我发现你代码里的栅格类写法有点小问题——xl l6是不对的哦,Materialize的响应式栅格类得写成xl6这种格式,不能分开写。下面给你两种靠谱的方法,保证在移动端和桌面端都能稳稳居中:

方法1:用Materialize自带的偏移类(最规范)

这是贴合Materialize设计思路的做法,利用栅格的offset偏移来让容器自动居中:

<body>
  <div class="container">
    <div id="mainContent" class="row">
      <!-- 手机端占满12列,平板及以上占6列,左右各偏移3列实现居中 -->
      <div id="root" class="col s12 m6 l6 xl6 offset-m3 offset-l3 offset-xl3"></div>
    </div>
  </div>
</body>

CSS可以简化,因为栅格系统已经帮我们处理了布局逻辑:

#mainContent {
  background-color: blue;
}
#root {
  background-color: white; /* 你要的白色盒子 */
  padding: 1.5rem; /* 加个内边距让内容不贴边,可选 */
}

方法2:用Flex布局强制居中(更灵活)

如果不想依赖栅格的偏移,直接给父容器加Flex布局也能快速实现居中,还能顺便搞定垂直居中:

<body>
  <div class="container">
    <div id="mainContent" class="row">
      <!-- 手机端12列,桌面端6列 -->
      <div id="root" class="col s12 l6 xl6"></div>
    </div>
  </div>
</body>

对应的CSS调整成这样:

#mainContent {
  background-color: blue;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中(如果需要让盒子在页面垂直中间的话) */
  min-height: 100vh; /* 让mainContent占满整个视口高度,配合垂直居中生效 */
}
#root {
  background-color: white;
  margin: 0; /* 移除默认margin避免和Flex布局冲突 */
}

小提醒

  • 如果你需要全屏宽度的容器,可以把container换成container-fluid,Materialize会自动适配全屏。
  • 栅格的尺寸缩写对应:s(手机<600px)、m(平板600-992px)、l(桌面992-1200px)、xl(大桌面>1200px),你可以根据实际需求调整列数和偏移量哦。

内容的提问来源于stack exchange,提问作者sander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:20:37