首页 > 解决方案 > CSS:为什么我的三列被拆分?

问题描述

我正在尝试使用 Next.js 制作一个反应应用程序,但我遇到了 CSS 问题。

我有以下定义的 home.module.css:

.grid_container {
  /* display: grid; */
  /* grid-template-columns: auto auto auto; */
  /* column-count: 3;
  align-items: flex-start; */
  /* align-content: space-evenly; */
  align-items: stretch;
  column-count: 3;
  /* column-gap: 500px; */
  border: solid;
  width: 100vw;
  height: 100vh;
}

.left_pane {
  justify-content: left;
  border-style: solid;
  float: left;
  width: 25%;
  height: 300px;
}

.center_pane {
  justify-content: left;
  border-style: solid;
  float: left;
  width: 50%;
  height: 300px;
}

.right_pane {
  justify-content: left;
  border-style: solid;
  width: 25%;
  float: right;
  height: 300px;
}

然后我有 index.js:

export default function Home() {
  return (
    <div className={styles.grid_container}>
      <div>
        <div className={styles.left_pane}>
          <h2>Left Pane</h2>
        </div>
        <div className={styles.center_pane}>
          <h2>Center Pane</h2>
        </div>
        <div className={styles.right_pane}>
          <h2>Right Pane</h2>
        </div>
      </div>
  )
}

结果: 为什么要包裹列?

为什么要这样包裹列?我想要占据整个框架的 3 列。

.grid_container {
  /* display: grid; */
  /* grid-template-columns: auto auto auto; */
  /* column-count: 3;
  align-items: flex-start; */
  /* align-content: space-evenly; */
  align-items: stretch;
  column-count: 3;
  /* column-gap: 500px; */
  border: solid;
  width: 100vw;
  height: 100vh;
}

.left_pane {
  justify-content: left;
  border-style: solid;
  float: left;
  width: 25%;
  height: 300px;
}

.center_pane {
  justify-content: left;
  border-style: solid;
  float: left;
  width: 50%;
  height: 300px;
}

.right_pane {
  justify-content: left;
  border-style: solid;
  width: 25%;
  float: right;
  height: 300px;
}
  <div class="grid_container">
    <div class="left_pane">
      <h2>Left Pane</h2>
    </div>

    <div class="center_pane">
      <h2>Center Pane</h2>
    </div>

    <div class="right_pane">
      <h2>Right Pane</h2>
    </div>
  </div>

标签: htmlcss

解决方案


使用 CSS 网格,您可以在属性中指定列宽grid-template-columns,并在属性中指定行高grid-template-rows。您不使用浮点数或width属性。此外,由于 div 元素已经是块状的,因此默认情况下它是全宽的。最后,容器内的元素被视为列。你在那里有一个额外的包装 div。

我建议看一下https://css-tricks.com/snippets/css/complete-guide-grid

.grid_container {
  display: grid;
  grid-template-columns: 25% 50% 25%;
  grid-template-rows: 100px;
  column-count: 3;
  column-count: 3;
  border: solid;
}

.grid_container .pane {
  justify-content: left;
  border-style: solid;
}
<div class="grid_container">
  <div class="pane">
    <h2>Left Pane</h2>
  </div>
  <div class="pane">
    <h2>Center Pane</h2>
  </div>
  <div class="pane">
    <h2>Right Pane</h2>
  </div>
</div>


推荐阅读