尝试创建如下所示的布局:
每个项目都是一个正方形(通过底部填充技术创建)。项目不应重叠。
无论我使用什么grid-area
道具,我在使用绿色元素时都遇到麻烦–它在左侧创建空白。
我在JSFiddle上进行了演示– http://jsfiddle.net/f2to1kyw/
甚至不用JS也可以创建这样的布局吗?
.container {
position: relative;
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(5, 1fr);
}
.item {
background: tomato;
width: 100%;
}
.item:before {
content: '';
padding-bottom: 100%;
display: block;
}
.item--big {
grid-area: 1 / 1 / 3 / 3;
}
.item--green {
background: #36926A
}
<div class="container">
<div class="item item--big"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item item--green"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
答案 0 :(得分:3)
Is it even possible to create such layout without JS?
Yes. There are a number of ways of doing this with CSS Grid.
grid-area
property:From MDN:
The
grid-area
CSS property is a shorthand property forgrid-row-start
,grid-column-start
,grid-row-end
andgrid-column-end
…
So the value of the grid-area
property for the green box would be: 2 / 4 / 4 / 6
which is shorthand for:
grid-row-start: 2;
grid-column-start: 4;
grid-row-end: 4;
grid-column-end: 6;
so the CSS rule would be:
.item--green {
grid-area: 2 / 4 / 4 / 6;
}
.container {
position: relative;
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(5, 1fr);
}
.item {
background: tomato;
width: 100%;
}
.item:before {
content: '';
padding-bottom: 100%;
display: block;
}
.item--big {
grid-area: 1 / 1 / 3 / 3;
}
.item--green {
background: #36926A;
grid-area: 2 / 4 / 4 / 6;
}
<div class="container">
<div class="item item--big"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item item--green"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
grid-column
/ grid-row
properties.container {
position: relative;
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(5, 1fr);
}
.item {
background: tomato;
width: 100%;
}
.item:before {
content: '';
padding-bottom: 100%;
display: block;
}
.item--big {
grid-column: 1 / span 2;
grid-row: 1 / span 2;
}
.item--green {
background: #36926A;
grid-column: 4 / span 2;
grid-row: 2 / span 2;
}
<div class="container">
<div class="item item--big"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item item--green"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
The Relevant Code:
.item--green {
grid-column: 4 / span 2; /* start at column 4 and span 2 columns */
grid-row: 2 / span 2; /* start at row 2 and span 2 rows */
}