When I add this code:
place-items: center;
My elements center, but only the text has a background-color applied.
When I remove this code:
place-items: center;
The background-color covers the whole column but the text isn't centered anymore.
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? How can I center the content and have the background color apply to the whole column?
Without place-items: center;
your grid items will get stretched to cover all the area (the default behavior in most of the cases) 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
(your grid item) instead of centering 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;
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With