如何在使用css网格时居中显示内容,并使背景覆盖整栏? [英] How to center content and make the background cover the full column when using CSS Grid?

查看:15
本文介绍了如何在使用css网格时居中显示内容,并使背景覆盖整栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我添加此代码时:

place-items: center;

我的元素居中,但只有文本应用了背景色。

当我删除此代码时:

place-items: center;

背景色覆盖整列,但文本不再居中。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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居中。不要忘了删除默认页边距以覆盖更大的区域:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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>

这篇关于如何在使用css网格时居中显示内容,并使背景覆盖整栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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