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

如何使用CSS子网格将不同div强制分配到指定列?

问题描述

需要实现两列布局,要求所有带有.title类的元素固定显示在左列,带有.card类的元素固定显示在右列,能否通过CSS subgrid实现这种将不同div强制分配到指定列的效果?

解决方案

可以通过CSS Grid的grid-column属性结合subgrid实现需求,核心是直接为两类元素指定对应列位置,同时用subgrid保证内部元素的行对齐。

修改后的代码如下:

CSS 代码

body {
  padding: 50px;
  font: 1em Helvetica Neue, Helvetica, Arial, sans-serif;
}

.grid {
  display: grid;
  gap: 20px;
  grid-template-columns: 0.3fr 1.4fr;
}

.card {
  border: 5px solid rgb(111, 41, 97);
  grid-row: auto / span 2;
  grid-column: 2; /* 强制.card显示在右列 */
  display: grid;
  gap: 0;
  grid-template-rows: subgrid;
}

.card h2 {
  background-color: rgba(111, 41, 97, .4);
  padding: 10px;
  margin: 0;
}

.card p {
  padding: 10px;
  margin: 0;
}

.title {
  border: 5px solid rgb(111, 41, 97);
  grid-row: auto / span 2;
  grid-column: 1; /* 强制.title显示在左列 */
  display: grid;
  gap: 0;
  grid-template-rows: subgrid;
}

.title h2 {
  background-color: rgba(11, 31, 27, .4);
  padding: 10px;
  margin: 0;
}

.title p {
  padding: 10px;
  margin: 0;
}

HTML 代码

<div class="grid">
  <article class="card">
    <h2>This is the heading</h2>
    <p>This is the body of the card.</p>
  </article>
  <article class="card">
    <h2>This should be in the right column only.</h2>
    <p>This is the body of the card.</p>
  </article>
  <article class="card">
    <h2>This is the heading</h2>
    <p>This is the body of the card.</p>
  </article>
  <article class="title">
    <h2>Title</h2>
    <p>Should be in the left column only.</p>
  </article>
  <article class="card">
    <h2>This is the heading</h2>
    <p>This is the body of the card.</p>
  </article>
  <article class="card">
    <h2>This is the heading</h2>
    <p>This is the body of the card.</p>
  </article>
  <article class="card">
    <h2>This is the heading</h2>
    <p>This is the body of the card.</p>
  </article>
  <article class="title">
    <h2>Title</h2>
  </article>
</div>

实现说明

  1. 主容器.grid定义两列布局,无需grid-template-areas,直接通过grid-column控制子元素的列位置。
  2. 为.title设置grid-column: 1,强制其始终显示在左列;为.card设置grid-column: 2,强制其始终显示在右列。
  3. 保留subgrid用于.title和.card内部的行布局,确保内部的h2和p能与其他元素的行对齐,维持整体布局一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:09:17