【问题标题】:Overlapping items in CSS GridCSS 网格中的重叠项
【发布时间】:2018-03-19 10:54:49
【问题描述】:

我正在尝试通过让两个元素在中途相互重叠来使用 css 网格进行响应式布局。在宽屏上,它们排成一排并水平重叠,但在窄屏上,它们应排成一列并垂直重叠。

这是我想要达到的目标的图示:

css 网格可以实现这种行为吗?这是我走了多远,但现在我一直在尝试获得垂直重叠。

CSS

.wrapper {
  background: white;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(444px, 1fr));
}

.wrapper__red, .wrapper__green {
  align-self: center;
}

.wrapper__red {
  z-index: 1;
  background: red;
}

.wrapper__green {
  justify-self: end;
  height: 100%;
  background: green;
}

HTML

<div class="wrapper">
  <h1 class="wrapper__red">Title text goes here</h1>
  <img class="wrapper__green" src="/a.jpg" />
</div>

【问题讨论】:

  • @PacoGómezCapón 我需要使用 css 网格来为 CMS 中的作者提供灵活性。然而,媒体查询的想法让我现在找到了一个可以接受的解决方案。
  • 我很可行,但你可能需要使用z-index

标签: html css css-grid


【解决方案1】:

在 CSS Grid 中,您可以创建重叠的网格区域。

网格通过基于行的放置让这一过程变得简单而轻松。

来自规范:

8.3. Line-based Placement

grid-row-startgrid-column-startgrid-row-endgrid-column-end 属性确定网格项的大小和位置 在网格内通过贡献一条线、一个跨度或什么都没有(自动) 到它的网格位置,从而指定内联开始, 其网格区域的 block-start、inline-end 和 block-end 边缘。

注意:调整下方演示的大小以从桌面视图过渡到移动视图

article {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-auto-rows: 50px;
  grid-gap: 5px;
}

section:nth-child(1) { grid-column: 1 / 4; grid-row: 1; z-index: 1; }
section:nth-child(2) { grid-column: 3 / 5; grid-row: 1; }
section:nth-child(3) { grid-column: 5 / 7; grid-row: 1; }

@media ( max-width: 500px ) {
   article { grid-template-columns: 100px; justify-content: center; }
   section:nth-child(1) { grid-row: 1 / 4; grid-column: 1; }
   section:nth-child(2) { grid-row: 3 / 5; grid-column: 1; }
   section:nth-child(3) { grid-row: 5 / 7; grid-column: 1; }
}

/* non-essential demo styles */
section:nth-child(1) { background-color: lightgreen; }
section:nth-child(2) { background-color: orange; }
section:nth-child(3) { background-color: aqua; }
section {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.2em;
}
<article>
  <section><span>1</span></section>
  <section><span>2</span></section>
  <section><span>3</span></section>
</article>

jsFiddle demo

【讨论】:

    【解决方案2】:

    就我而言,我补充说:

    section {
        overflow: hidden;
    }
    

    到我的网格块,它给了我相同的高度,无论是否有任何包装。

    <article>
      <section><span>1</span></section>
      <section><span>2</span></section>
      <section><span>3</span></section>
    </article>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 2018-12-29
      • 2019-11-23
      相关资源
      最近更新 更多