CSS网格中的重叠项目 [英] Overlapping items in CSS Grid

查看:161
本文介绍了CSS网格中的重叠项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使两个元素彼此重叠的方式来使用css网格进行响应式布局.在宽屏上,它们成行并水平重叠;而在窄屏上,它们应成一列并垂直重叠.

I'm trying to do a responsive layout with css grid by getting two elements to overlap each other halfway. On wide screens they are in one row and overlapping horizontally, but on narrow screens they should be in one column and overlap vertically.

以下是我要实现的目标的说明:

Here is an illustration of what I'm trying to achieve:

使用CSS网格是否可能发生这种情况?这是我所走的距离,但现在我想尝试获得垂直重叠.

Is this behavior possible with css grid? Here is how far I got but now I'm stuck trying to get the vertical overlap.

.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>

推荐答案

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

In CSS Grid you can create overlapping grid areas.

网格使基于行的放置使这一过程变得简单而容易.

Grid makes this simple and easy with line-based placement.

根据规范:

8.3.基于行 展示位置

8.3. Line-based Placement

grid-row-startgrid-column-startgrid-row-endgrid-column-end属性确定网格项目的大小和位置 在网格中通过添加一条线,一个跨度或什么都不做(自动) 到其网格位置,从而指定inline-start, 网格区域的块起点,行内终点和块终点边缘.

The grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties determine a grid item’s size and location within the grid by contributing a line, a span, or nothing (automatic) to its grid placement, thereby specifying the inline-start, block-start, inline-end, and block-end edges of its grid area.

注意:在下面重新调整演示大小,以从台式机视图过渡到移动视图

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>

这篇关于CSS网格中的重叠项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆