问题
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?
回答1:
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>
来源:https://stackoverflow.com/questions/50841334/how-to-add-background-color-when-using-css-grid