【问题标题】:How to center content and make the background cover the full column when using CSS Grid?使用 CSS Grid 时如何使内容居中并使背景覆盖整列?
【发布时间】:2018-11-23 06:40:11
【问题描述】:

当我添加这段代码时:

place-items: center;

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

当我删除此代码时:

place-items: center;

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

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>

为什么会这样?如何使内容居中并将背景颜色应用于整个列?

【问题讨论】:

    标签: css css-grid


    【解决方案1】:

    没有place-items: center;,您的网格项目将被拉伸以覆盖所有区域(大多数情况下的默认行为),这就是背景将覆盖大面积的原因:

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

    为避免这种情况,您可以将p(您的网格项目)中的内容居中,而不是将p 居中。不要忘记同时删除默认边距以覆盖更大的区域:

    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>

    【讨论】:

    • 当我使用 display:grid;而不是 display:inline-grid; ,我得到相同的结果。哪个更好用?为什么?你为什么使用 display:inline-grid;在这里?
    • @GalibHasanov 在这种情况下,两者的行为相同...区别与块和内联块完全相同...如果您将内联网格与兄弟元素一起使用,它们将被放置在同一行不像网格......所以在这里你也改变为网格,因为每个元素都在一个网格区域内
    • 在您的评论中提到子元素需要display: griddisplay: inline-grid 的答案中可能值得一提;这是重要的信息,但 cmets 是短暂的。
    猜你喜欢
    • 2022-06-11
    • 1970-01-01
    • 2021-02-28
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多