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

如何在table表格中居中div元素,解决移动端布局居中异常问题

移动端布局居中解决方案

现有样式失效原因

  • 表格行<tr>本身不支持margin属性,你给.mobile tr设置的margin: auto不会生效
  • 你给移动端表格设置了100%宽度,表格会自动拉伸列宽铺满容器,第二行只有5个单元格时,每个单元格宽度会被拉宽,内部的圆形元素默认靠左,自然不会居中
  • text-align: center写在tr上不会作用于内部块级元素,需要设置在单元格<td>上才会生效

修复方案

只需要修改媒体查询内的样式即可,无需改动原有HTML结构:

.item{
  background-color: cyan;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: table;
}
.item > div{
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.mobile{
  display: none;
}
@media only screen and (max-width: 600px) {
  .desktop{
      display: none;
  }
  .mobile{
      display: table;
      /* 覆盖行内的100%宽度设置,让表格自适应内容宽度 */
      width: auto;
      /* 表格整体水平居中 */
      margin: 10px auto 0;
  }
  .mobile td{
      /* 单元格内部内容居中 */
      text-align: center;
      /* 可选:增加单元格左右间距,避免圆形元素贴在一起 */
      padding: 0 6px;
  }
}

修改后移动端的两行圆形元素会整体居中,符合预期效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:18:03