首页 > 解决方案 > flexbox按钮的子节点不以百分比应用高度

问题描述

我有以下代码

.flex {
  display: flex;
  width: 100%;
  height: 48px;
  background: black;
  flex-direction: row
}
.flex-item {
  height: 100%;
  background: grey
}
<button class="flex">
  <div class="flex-item">
    Click Me
  </div>
</button>

问题是,父节点<button>带有flex-direction: row,子元素不接受百分比高度。百分比高度仅在父节点为<div>

标签: htmlcssflexbox

解决方案


* {
  margin: 0;
  padding: 0;
}

.flex {
  display: flex;
  width: 100%;
  height: 48px;
  background: black;
  flex-direction: row;
  border: none;
}

.flex-item {
  height: 100%;
  background: grey;
}
<button class="flex">
  <div class="flex-item">
    Click Me
  </div>
</button>

但如果您使用flex,最好使用它的功能添加到父级 align-items: stretch;

* {
  margin: 0;
  padding: 0;
}

.flex {
  display: flex;
  width: 100%;
  height: 48px;
  background: black;
  flex-direction: row;
  align-items: stretch;
  border: none;
}

.flex-item {
  background: grey;
}
<button class="flex">
  <div class="flex-item">
    Click Me
  </div>
</button>


推荐阅读