并排对齐 CSS 列
Align CSS columns side by side
如果我在 2 列布局中有以下 HTML,如何使用 CSS 网格将它们并排对齐?
.grid {
display: grid;
grid-template-columns: 1fr;
grid-row-gap: 1.25em;
}
aside {
grid-column: 1;
grid-row: 1;
text-align: left;
}
article {
grid-column: 1;
grid-row: 2;
text-align: left;
}
<article class="content">
<h2>{{ page.title }}</h2>
<p>{{ content }}</p>
</article>
<aside class="sidebar">
<h3>{{ page.date | date: '%B %-d, %Y' }}</h3>
<p>{{ page.tags | array_to_sentence_string }}</p>
</aside>
第一个问题是您使用网格定义了一个 class 但后来没有在您的 HTML 中使用它,但这可能只是您的 MCVE 中的错字。
第二个问题是,如果您想在 grid-template-columns
中设置宽度,您需要为每一列指定宽度,使用重复,或者两者兼而有之。您正在尝试使用两列,但只为一列指定了宽度。
第三个问题是您对两个元素都使用了 grid-column: 1;
。根据 MDN web docs:
The grid-column CSS property is a shorthand property for grid-column-start
and grid-column-end
specifying a grid item's size and location* within the grid row by contributing a line, a span, or nothing (automatic) to its grid placement, thereby specifying the inline-start and inline-end edge of its grid area.
*强调
通过将它们都设置为 1,您可以将它们放在同一列中。在下面的代码片段中,我将网格模板更改为 1fr,重复 2,并将 aside
设置为第二列而不是第一列。
.grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-row-gap: 1.25em;
}
aside {
grid-column: 2;
text-align: left;
}
article {
grid-column: 1;
text-align: left;
}
<main class="grid">
<article class="content">
<h2>{{ page.title }}</h2>
<p>{{ content }}</p>
</article>
<aside class="sidebar">
<h3>{{ page.date | date: '%B %-d, %Y' }}</h3>
<p>{{ page.tags | array_to_sentence_string }}</p>
</aside>
</main>
如果我在 2 列布局中有以下 HTML,如何使用 CSS 网格将它们并排对齐?
.grid {
display: grid;
grid-template-columns: 1fr;
grid-row-gap: 1.25em;
}
aside {
grid-column: 1;
grid-row: 1;
text-align: left;
}
article {
grid-column: 1;
grid-row: 2;
text-align: left;
}
<article class="content">
<h2>{{ page.title }}</h2>
<p>{{ content }}</p>
</article>
<aside class="sidebar">
<h3>{{ page.date | date: '%B %-d, %Y' }}</h3>
<p>{{ page.tags | array_to_sentence_string }}</p>
</aside>
第一个问题是您使用网格定义了一个 class 但后来没有在您的 HTML 中使用它,但这可能只是您的 MCVE 中的错字。
第二个问题是,如果您想在 grid-template-columns
中设置宽度,您需要为每一列指定宽度,使用重复,或者两者兼而有之。您正在尝试使用两列,但只为一列指定了宽度。
第三个问题是您对两个元素都使用了 grid-column: 1;
。根据 MDN web docs:
The grid-column CSS property is a shorthand property for
grid-column-start
andgrid-column-end
specifying a grid item's size and location* within the grid row by contributing a line, a span, or nothing (automatic) to its grid placement, thereby specifying the inline-start and inline-end edge of its grid area.
*强调
通过将它们都设置为 1,您可以将它们放在同一列中。在下面的代码片段中,我将网格模板更改为 1fr,重复 2,并将 aside
设置为第二列而不是第一列。
.grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-row-gap: 1.25em;
}
aside {
grid-column: 2;
text-align: left;
}
article {
grid-column: 1;
text-align: left;
}
<main class="grid">
<article class="content">
<h2>{{ page.title }}</h2>
<p>{{ content }}</p>
</article>
<aside class="sidebar">
<h3>{{ page.date | date: '%B %-d, %Y' }}</h3>
<p>{{ page.tags | array_to_sentence_string }}</p>
</aside>
</main>