使用CSS网格时如何添加背景色? [英] How to add background-color when using css grid?

查看:286
本文介绍了使用CSS网格时如何添加背景色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我添加以下代码时:

  place-items:center; 

仅文本的背景颜色正在更改。



当我删除此代码时:

  place-items:center; 

整列的颜色正在改变。



< pre class = snippet-code-css lang-css prettyprint-override> 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>  



为什么

解决方案

没有 place-items:center; 您的网格项目将被拉伸以覆盖所有区域,这就是背景将覆盖较大区域的原因:





使用 place-items:center; 您的网格项目将适合其内容,并将其放置在中心;因此,背景将仅覆盖文本。





为避免这种情况,您可以将内容放在 p 内部,而不是将 p 置于中心。不要忘记也删除默认边距以覆盖更大的区域:



  main {显示:网格; grid-template-columns:repeat(4,1fr); grid-template-rows:100px; grid-gap:20px;} p {background-color:#eee;显示:内联网格;地点:中心; margin:0;}  

 < main> < p> box1< / p> < p> box2< / p> < p> box3< / p> < p&box; box4< / p>< / main>  


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?

解决方案

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>

这篇关于使用CSS网格时如何添加背景色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆