css - 为什么 flex 按钮的 child 不能拉伸(stretch)到全高?

标签 css flexbox

<分区>

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

这是带有 button 标记的片段(不拉伸(stretch)):

.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 标记(拉伸(stretch))的片段:

.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>

我还在 .content 类中尝试了 height: 100% oir self-align: stretch,但没有成功。

最佳答案

根据这个答案:Flexbox not working on button or fieldset elements ,在某些浏览器中,您不能将按钮的显示属性设置为 blockinline-block 以外的任何内容。

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

(注意:如前所述,按钮内的 div 不是正确的 HTML... 考虑用 span 替换它。)

.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>

关于css - 为什么 flex 按钮的 child 不能拉伸(stretch)到全高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59411088/

上一篇:css - Safari flexbox : div inside of a button which is a flex item doesn't get proper height

下一篇:javascript - 重新生成网格时只运行一次 CSS 动画

相关文章:

css - Flexbox:试图在段落元素之上获取 H1 元素

jquery - 更改单个div的高度(Flexbox)

html - Flexbox:如何优化 Material 设计仪表板布局

jquery - 如何克隆表格标题行中除最后一列之外的每一列

css - 如何在 sass 中编写媒体查询?

html - 我如何在 less 文件中写 a:hover::before ?

html - 对齐内容 - 在 bootstrap 中的导航栏内

html - 3级CSS子菜单悬停状态

html - 元标记?表单域放大焦点但在移动设备上聚焦时不会取消缩放?

html - 为什么 flex 元素不缩小过去的内容大小?