英文:
Css Grid Dynamic layouts
问题
我正在尝试创建一个包含1-4个元素的动态网格布局。他们在 https://css-tricks.com/exploring-css-grids-implicit-grid-and-auto-placement-powers/ 的“dynamic layouts”部分实现了与我所需的类似的东西,但略有不同。
这个布局的CSS代码如下:
.grid {
display: grid;
}
.grid :nth-child(2) {
grid-column-start: 2;
}
.grid :nth-child(3):last-child {
grid-column-start: span 2;
}
我试图做类似但不同的事情,但我无法实现。这是我想要实现的效果图片:
英文:
I am trying to make a dynamic grid layout containing 1-4 elements. They achieved something close to what I am looking for at https://css-tricks.com/exploring-css-grids-implicit-grid-and-auto-placement-powers/ under the "dynamic layouts" section. But slightly different.
The CSS for this layout:
.grid {
display: grid;
}
.grid :nth-child(2) {
grid-column-start: 2;
}
.grid :nth-child(3):last-child {
grid-column-start: span 2;
}
I am trying to do something similar but different, but I cannot get it. This is a picture of what I want to achieve:
答案1
得分: 3
你可以使用CSS的nth-last-child选择器来识别第一个子元素是三个子元素中的第一个。
.grid {
display: grid;
}
.grid :nth-child(2) {
grid-column-start: 2;
}
.grid :nth-child(1):nth-last-child(3) {
grid-row-start: span 2;
}
.grid {
width: 300px;
aspect-ratio: 1;
grid-gap: 5px;
outline: 2px solid red;
vertical-align: top;
margin: 10px;
counter-reset: num;
}
.grid * {
border: 2px solid;
font-size: 30px;
box-sizing: border-box;
font-family: sans-serif;
display: grid;
place-content: center;
}
.grid *:before {
content: counter(num);
counter-increment: num;
}
<div class="grid">
<div></div>
</div>
<div class="grid">
<div></div>
<div></div>
</div>
<div class="grid">
<div></div>
<div></div>
<div></div>
</div>
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
英文:
You can use the CSS nth-last-child selector to spot when the first child is the first of three children.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.grid {
display: grid;
}
.grid :nth-child(2) {
grid-column-start: 2;
}
.grid :nth-child(1):nth-last-child(3) {
grid-row-start: span 2;
}
/**/
.grid {
width: 300px;
aspect-ratio: 1;
grid-gap: 5px;
outline: 2px solid red;
vertical-align: top;
margin: 10px;
counter-reset: num;
}
.grid * {
border: 2px solid;
font-size: 30px;
box-sizing: border-box;
font-family: sans-serif;
display: grid;
place-content: center;
}
.grid *:before {
content: counter(num);
counter-increment: num;
}
<!-- language: lang-html -->
<div class="grid">
<div></div>
</div>
<div class="grid">
<div></div>
<div></div>
</div>
<div class="grid">
<div></div>
<div></div>
<div></div>
</div>
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论