【问题标题】:How can I make a CSS grid fill the height of the parent element? [duplicate]如何使 CSS 网格填充父元素的高度? [复制]
【发布时间】:2021-04-28 17:23:10
【问题描述】:

我希望使用 CSS 网格制作一个按钮,其中元素填充容器的整个高度:

button {
  display: grid;
  height: 50px;
  grid-auto-flow: column;
  align-items: center;
}

.one {
  color: white;
  background-color: purple;
  border-right: 1px solid red;
}
<button>
  <span class="one">one</span>
  <span class="two">two</span>
</button>

从检查器可以看出,这是一行,没有填满容器的高度:

我想让网格填充容器,所以容器的整个左侧都是紫色的。

【问题讨论】:

  • 请不要停留在重复的标题上,阅读它,看看问题是否相同。
  • @TemaniAfif 确定并完成。它不是重复的。
  • 目标的原始措辞具有误导性,但实际上是重复的。为了清楚起见,它已经过编辑,现在应该更清楚了。我还添加了第二个欺骗目标,它解释了为什么内联元素不会占据容器的全部高度以及如何让它们这样做。

标签: css css-grid


【解决方案1】:

您可以在网格内的任何项目上使用height: 100%; 来完成

工作示例:

button {
  display: grid;
  height: 50px;
  grid-auto-flow: column;
  align-items: center;
}

.one {
  color: white;
  background-color: purple;
  border-right: 1px solid red;
  height: 100%;
}
<button>
  <span class="one">one</span>
  <span class="two">two</span>
</button>

如果您希望文本垂直居中,您可以使用display: griddisplay: inline-gridalign-items: center

工作示例:

button {
  display: grid;
  height: 50px;
  grid-auto-flow: column;
  align-items: center;
}

.one {
  color: white;
  background-color: purple;
  border-right: 1px solid red;
  height: 100%;
  align-items: center;
  display: grid;
}
<button>
  <span class="one">one</span>
  <span class="two">two</span>
</button>

【讨论】:

  • 谢谢!是否可以使用grid 保持文本居中而不是更改为inline-flex
  • 是的,display: grid - 我改变了答案...
【解决方案2】:

button {
  display: grid;
  height: 50px;
  grid-auto-flow: column;
  align-items: center;
}

.one {
  color: white;
  background-color: purple;
  border-right: 1px solid red;
}

span {
  display: flex;
  align-items: center;
  height: 100%;
}
<button>
  <span class="one">one</span>
  <span class="two">two</span>
</button>

【讨论】:

  • 这很好,但似乎与现有答案相同。
猜你喜欢
  • 2021-07-22
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2020-01-08
  • 1970-01-01
  • 2011-05-04
相关资源
最近更新 更多