How to add background-color when using css grid?

风格不统一 提交于 2019-12-22 08:40:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!