我正在尝试将一个绝对简单的布局放在一起,看起来我被一个p标签所阻挠,它正在将容器拉伸到网格布局之外,而不是预期的行为(包装)。
以下是一些基本代码:
HTML:
<div class="top-level-wrapper">
<header>I am a header!</header>
<main>
<h3>Some page title</h3>
<p>
Some text.
</p>
</main>
<footer>I am a footer!</footer>
</div>
CSS:
html, body {
margin: 0 auto;
}
/* Layout stuff. */
header {grid-area: h;}
footer {grid-area: f;}
main {grid-area:m;}
.top-level-wrapper {
display: grid;
grid-template-areas:
"h h h h h"
". m m m ."
"f f f f f";
}
我的理解是,这个网格模板区域基本上是这样说:“每行有5个相等的小数单位,主要在所有时间占据中间三个。
然而,实际发生的是,如果“某些文本”被延长,模板就会中断。
如何将网格配置为实际做正确的事情,无论其内容在默认情况下的行为如何?
答案 0 :(得分:2)
您需要包含grid-template-columns
属性:
html, body {
margin: 0 auto;
}
/* Layout stuff. */
header {grid-area: h;}
footer {grid-area: f;}
main {grid-area:m;}
.top-level-wrapper {
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-template-areas:
"h h h h h"
". m m m ."
"f f f f f";
}
/* Cosmetics only - you can ignore what's below here. */
header, footer {
background-color: darkblue;
color: white;
}
main {
border: 3px solid red;
background-color: grey;
}
&#13;
<div class="top-level-wrapper">
<header>I am a header!</header>
<main>
<h3>Some page title</h3>
<p>
Some text. And some more, and more, and more, until this paragraph, which really ought to be wrapping, will instead lengthen the main section and break the template's contract.
</p>
</main>
<footer>I am a footer!</footer>
</div>
&#13;
答案 1 :(得分:2)
您正在使用grid-template-areas
来构建网格。这列出了行和列。
但是,如果没有grid-template-columns
来定义每列的宽度,它们将默认为auto
(即内容长度)。第二行中的第一列和最后一列没有内容,因此它们只是折叠。然后,三个中间列占用行中的所有空间。
您需要使用grid-template-columns
来获得所需的行为。如果将每列设置为1fr
,则该行将分为五个等宽列
html, body {
margin: 0 auto;
}
/* Layout stuff. */
header {grid-area: h;}
footer {grid-area: f;}
main {grid-area:m;}
.top-level-wrapper {
display: grid;
grid-template-areas:
"h h h h h"
". m m m ."
"f f f f f";
grid-template-columns: repeat(5, 1fr); /* NEW */
}
/* Cosmetics only - you can ignore what's below here. */
header, footer {
background-color: darkblue;
color: white;
}
main {
border: 3px solid red;
background-color: grey;
}
<div class="top-level-wrapper">
<header>I am a header!</header>
<main>
<h3>Some page title</h3>
<p>
Some text. And some more, and more, and more, until this paragraph, which really ought to be wrapping, will instead lengthen the main section and break the template's contract.
</p>
</main>
<footer>I am a footer!</footer>
</div>