首页 > 解决方案 > 如何让 CSS 网格填充父元素的高度?

问题描述

我希望使用 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>

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

在此处输入图像描述

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

标签: csscss-grid

解决方案


您可以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: gridordisplay: 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>


推荐阅读