Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

How to center content and make the background cover the full column when using 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...