使用CSS网格时如何添加背景色? [英] How to add background-color when using css grid?
问题描述
当我添加以下代码时:
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;
您的网格项目将被拉伸以覆盖所有区域,这就是背景将覆盖较大区域的原因:
使用 place-items:center;
您的网格项目将适合其内容,并将其放置在中心;因此,背景将仅覆盖文本。
为避免这种情况,您可以将内容放在 p
内部,而不是将 p
置于中心。不要忘记也删除默认边距以覆盖更大的区域:
main {显示:网格; grid-template-columns:repeat(4,1fr); grid-template-rows:100px; grid-gap:20px;} p {background-color:#eee;显示:内联网格;地点:中心; margin:0;}
< main> < p> box1< / p> < p> box2< / p> < p> box3< / p> < p&box; box4< / p>< / main>
When I add this code:
place-items: center;
Only the background color of the text is changing.
When I remove this code:
place-items: center;
The color of the whole column is changing.
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>
Why is this happening?
Without place-items: center;
your grid itmes will get stretched to cover all the area that's why the background will the cover a big area:
With place-items: center;
your grid item will fit their content and they will be placed in the center; thus the background will cover only the text.
To avoid this, you can center the content inside the p
instead of centring the p
. Don't forget to also remove the default margin to cover a bigger area:
main {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 100px;
grid-gap: 20px;
}
p {
background-color: #eee;
display: inline-grid;
place-items: center;
margin: 0;
}
<main>
<p>box1</p>
<p>box2</p>
<p>box3</p>
<p>box4</p>
</main>
这篇关于使用CSS网格时如何添加背景色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!