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

如何使用CSS媒体查询调整Footer的Div布局(平板适配)

平板端Footer布局适配解决方案

需求说明

桌面端Footer为5列横向均匀分布;平板设备(宽度≤960px)时,前3列占满一行,第4列靠左、第5列靠右排列在第二行,且不想用空div来实现。

原代码

JSX结构:

<footer>
    <div className="footer-content">
        <div className="col">1</div>
        <div className="col">2</div>
        <div className="col">3</div>
        <div className="col">4</div>
        <div className="col">5</div>
    </div>
    <div className="another-stuff">
        another stuff
    </div>
</footer>

桌面端CSS:

.footer-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 7%;
}

.col {
  display: flex;
  flex-direction: column;
}

之前尝试的代码会导致第4、5列居中,无法达到目标布局。

两种可行解决方案

方案一:Flex布局实现

通过媒体查询调整flex属性,利用margin-left: auto让第5列靠右:

.footer-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 7%;
}

.col {
  display: flex;
  flex-direction: column;
}

/* 平板设备适配 */
@media (max-width: 960px) {
  .footer-content {
    flex-wrap: wrap;
    justify-content: flex-start; /* 行内元素靠左对齐 */
  }

  .footer-content .col {
    flex: 1 0 33%; /* 前3列各占1/3宽度 */
    margin-bottom: 1rem; /* 可选:增加上下间距 */
  }

  /* 调整第4、5列的宽度和位置 */
  .footer-content .col:nth-child(4),
  .footer-content .col:nth-child(5) {
    flex: 0 1 auto; /* 取消自动占宽,按内容宽度显示 */
    width: auto;
  }

  .footer-content .col:nth-child(5) {
    margin-left: auto; /* 强制第5列靠右侧 */
  }
}

方案二:Grid布局实现

用Grid的列定位更直观,直接指定第4、5列的位置:

.footer-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 7%;
}

.col {
  display: flex;
  flex-direction: column;
}

/* 平板设备适配 */
@media (max-width: 960px) {
  .footer-content {
    display: grid;
    grid-template-columns: repeat(3, 1fr); /* 分成3等列 */
    gap: 1rem; /* 列之间的间距 */
  }

  /* 指定第4、5列的网格位置 */
  .footer-content .col:nth-child(4) {
    grid-column: 1 / 2; /* 第4列放在第一格 */
  }

  .footer-content .col:nth-child(5) {
    grid-column: 3 / 4; /* 第5列放在第三格 */
  }
}

说明

  • Flex方案通过margin-left: auto特性,在不添加空元素的前提下,让第5列自动靠右,第4列默认靠左,实现需求布局。
  • Grid方案则通过明确的网格列定位,更清晰地控制每一列的位置,代码可读性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:25:24