是否可以在一个CSS-Grid-Cell中放置多个元素而不重叠? [英] Is it possible to place more than one element into a CSS-Grid-Cell without overlapping?

查看:101
本文介绍了是否可以在一个CSS-Grid-Cell中放置多个元素而不重叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三列和一行,我想将每个网格元素放入三个结果单元之一。这就是我想要的,使用三个容器元素:

I have three columns and one row and I want to place each grid-element into one of the three resulting cells. This is what I want, using three container-elements:

main {
  display: grid;
  grid-template-columns: 33% 33% auto;
  grid-gap: 15px;
}

.container {
  background-color: orange;
}

.element {
  transition: height 0.5s;
  margin: 15px;
  height: 100px;
  background-color: grey;
}

.element:hover {
  height: 200px;
}

<main>
  <div class="container">
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
  </div>

  <div class="container">
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
  </div>

  <div class="container">
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
  </div>
</main>

我知道可以使用三个容器来实现,但是我要避免使用任何不是真正必需的东西。

I know that this would be possible using three containers, but I want to avoid using anything which isn't really 'necessary'.

使用多行并将元素从一行扩展到两行或三行不会像我在上面的示例中那样平滑。但是,使用多个行并只是调整元素的大小会调整整个行的大小,这会影响下一行的位置。

Using multiple rows and expanding an element from one to two or three rows wouldn't be as "smooth" as in the example I posted above. However, using multiple rows and just resizing an element resizes the complete row, which affects the position of the next row.

一种解决方案是将每个元素放置在相同的位置列到同一单元格中。这样,最多只有一行,并且每次调整元素大小时,它只会影响元素在同一列中的位置,这正是我想要的。

A solution would be to place each element of the same column into the same cell. That way there's one row at most, and each time an element gets resized, it only affects the position of the elements in the same column, which is exactly what I want.

在同一单元格中放置多个元素时的问题是它们保持重叠,而我发现没有办法阻止它们这样做。

The problem when placing multiple elements in the same cell is that they keep overlapping and I found no way to stop them from doing that.

那么有一种放置方法

推荐答案

分配给网格的元素不会在同一个单元格中有多个元素而不会仅使用css-grid布局重叠吗?应用任何流程,就无法解决。它们将被一拍一拍地放在网格上,就像它们被完全定位一样。但是,它们将服从任何z-index值。

Elements that are assigned to the grid will not have any flow applied, there is no way around it. They will be slapped onto the grid one over the other, just as if they were absolutely positioned. They will obey any z-index value, though.

这是因为规范明确声明,如果将元素分配给相交的区域,则允许重叠。

This is because the specification explicitly states that the elements are allowed to overlap, if they are assigned to areas that intersect.

此外,规范鼓励将网格与弹性框混合在一起,以获得更复杂的布局。

Also, the specification encourages to mix grid with flexboxes, to obtain more complex layouts.

这篇关于是否可以在一个CSS-Grid-Cell中放置多个元素而不重叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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