问题
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.
So is there a way to place multiple elements in the same cell without overlapping using only the css-grid layout?
回答1:
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.
来源:https://stackoverflow.com/questions/45264354/is-it-possible-to-place-more-than-one-element-into-a-css-grid-cell-without-overl