gpt4 book ai didi

css - 使用 CSS Grid 时如何让内容居中并让背景覆盖整个栏目?

转载 作者:太空狗 更新时间:2023-10-29 12:22:30 24 4
gpt4 key购买 nike

当我添加这段代码时:

place-items: center;

我的元素居中,但只有文本应用了背景色。

当我删除这段代码时:

place-items: center;

背景颜色覆盖了整个列,但文本不再居中。

main {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 100px;
grid-gap: 20px;
place-items: center;
}

p {
background-color: #eee;
}
<body>
<main>
<p>box1</p>
<p>box2</p>
<p>box3</p>
<p>box4</p>
</main>
</body>

为什么会这样?如何将内容居中并将背景颜色应用到整个列?

最佳答案

如果没有 place-items: center;,您的网格元素将被拉伸(stretch)以覆盖所有区域(大多数情况下的默认行为),这就是背景将覆盖大面积的原因:

enter image description here

使用 place-items: center; 你的网格元素将适合它们的内容并且它们将被放置在中心;因此背景将只覆盖文本。

enter image description here

为避免这种情况,您可以将内容置于p(您的网格项)的中心,而不是将p 置于中心。不要忘记也删除默认边距以覆盖更大的区域:

main {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 100px;
place-items: stretch; /* this is the default value in most of the cases so it can be omitted */
grid-gap: 20px;
}

p {
background-color: #eee;
/* center the content (you can also use flexbox or any common solution of centering) */
display: grid; /* OR inline-grid */
place-items: center;
/**/
margin: 0;
}
<main>
<p>box1</p>
<p>box2</p>
<p>box3</p>
<p>box4</p>
</main>

关于css - 使用 CSS Grid 时如何让内容居中并让背景覆盖整个栏目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50841334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com