为什么弹性按钮的子项不能伸展到最高高度?

时间:2019-12-19 13:47:54

标签: css flexbox

我正在尝试在按钮内使用水平flex元素,但它们不会垂直拉伸到按钮高度。为什么?

以下是带有button标记的代码段(不会拉伸):

.container {
  width: 200px;
  height: 100px;
}

.btn {
  
  width: 100%;
  height: 100%;
  padding: 0;
  background: transparent;
  border: 1px solid yellow;
  display: flex;
  align-items: stretch;
}

.content {
  flex: 1;
  color: white;
}

.red { background: red; }
.green { background: green; }
.blue { background: blue; }
<div class="container">
  <button class="btn">
    <div class="content red">Ho</div>
    <div class="content green">Ho</div>
    <div class="content blue">Ho</div>
  </button>
</div>

以下是带有div标记的代码段(可以拉伸):

.container {
  width: 200px;
  height: 100px;
}

.btn {
  
  width: 100%;
  height: 100%;
  padding: 0;
  background: transparent;
  border: 1px solid yellow;
  display: flex;
  align-items: stretch;
}

.content {
  flex: 1;
  color: white;
}

.red { background: red; }
.green { background: green; }
.blue { background: blue; }
<div class="container">
  <div class="btn">
    <div class="content red">Ho</div>
    <div class="content green">Ho</div>
    <div class="content blue">Ho</div>
  </div>
</div>

我还在height: 100%类中尝试过self-align: stretch的{​​{1}},但是没有成功。

1 个答案:

答案 0 :(得分:0)

根据以下答案:Flexbox not working on button or fieldset elements,在某些浏览器中,您无法将按钮的显示属性设置为blockinline-block以外的任何其他属性。

建议的解决方案是添加一个包装器:

(注意:正如已经注释过的,按钮内的div是不正确的HTML ... 考虑将其替换为跨度。)

.container {
  width: 200px;
  height: 100px;
}

.btn {
  
  width: 100%;
  height: 100%;
  padding: 0;
  background: transparent;
  border: 1px solid yellow;
}

.wrapper{
  display: flex;
  height: 100%;
  align-items: stretch;
}

.content {
  flex: 1;
  color: white;
}

.red { background: red; }
.green { background: green; }
.blue { background: blue; }
<div class="container">
  <button class="btn">
    <div class="wrapper">
      <div class="content red">Ho</div>
      <div class="content green">Ho</div>
      <div class="content blue">Ho</div>
    </div>
  </button>
</div>