Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center content and make the background cover the full column when using CSS Grid?

Tags:

css

css-grid

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?

like image 714
black Avatar asked Jun 13 '18 15:06

black


1 Answers

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:

enter image description here

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.

enter image description here

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>
like image 186
Temani Afif Avatar answered Sep 28 '22 13:09

Temani Afif