我正在尝试使用CSS网格,这就是我正在构建的布局:
.grid {
display: grid;
align-items: center;
grid-template-columns: 1fr 4rem 1fr;
grid-template-rows: 1rem 1fr 1rem;
max-width: 900px;
margin: 0 auto;
}
.text {
/*
// Ideally, this should be
grid-area: text
*/
grid-column: 1 / 3;
grid-row: 2 / 3;
/* Fix z-index */
position: relative;
padding: 4rem;
background-color: #fff;
}
.image {
/*
// Ideally, this should be
grid-area: image;
*/
grid-column: 2 / 4;
grid-row: 1 / -1;
background-color: lightgray;
padding: 1rem;
/* Center das image */
display: flex;
justify-content: center;
}
/* Basic body */
body {
background-color: #fafafa;
font-family: sans-serif;
padding: 2rem;
}
img {
max-width: 100%;
height: auto;
}
<div class="grid">
<div class="text">One morning, when bobby woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his leg like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into
stiff sections.
</div>
<div class="image">
<img src="http://unsplash.it/400/400" />
</div>
</div>
(最好以整页预览...)
我想避免的事情:
.text
和.image
目前都使用grid-column: * / *;
语法,而我想使用grid-area: text
和grid-area: image;
。
是否可以将grid-template-{columns|rows}
定义为重叠区域?我尝试使用second way of defining grid areas
,但这似乎不起作用。
看起来你不能用那种语法做[a-start] [b-start] [a-end] [b-end]
,或者至少我没有做到。
所以 - 有没有办法使用命名区域创建重叠网格?
我试图纯粹使用命名区域 - 这样可以更容易推理响应式布局代码,而不是在媒体查询中多次重复自己。
修改 找到答案是因为@vals答案如下。
这似乎工作得很好,我可能在以前的尝试中出现了语法错误:
grid-template-columns: [text-start] 1fr [image-start] 4rem [text-end] 1fr [image-end];
grid-template-rows: [image-start] 1rem [text-start] 1fr [text-end] 1rem [image-end];
答案 0 :(得分:6)
至少在更基本的布局中,它似乎对我有用:
.container {
border: solid 1px green;
height: 180px;
width: 300px;
display: grid;
grid-template-columns: [left-start] 100px [right-start] 100px [left-end] 100px [right-end];
grid-template-rows: [left-start] 60px [right-start] 60px [left-end] 60px [right-end];
}
.left {
grid-area: left;
background-color: red;
}
.right {
grid-area: right;
background-color: lightgray;
opacity: 0.5;
}
<div class="container">
<div class="left">
</div>
<div class="right">
</div>
</div>