【发布时间】:2017-08-06 17:50:17
【问题描述】:
我正在试验 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];
【问题讨论】: