【问题标题】:Why don't children of flex button stretch to full height? [duplicate]为什么弹性按钮的孩子不能伸展到全高? [复制]
【发布时间】:2019-12-19 13:47:54
【问题描述】:

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

这是带有button 标记的sn-p(不拉伸):

.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 标记的sn-p(会拉伸):

.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,但没有成功。

【问题讨论】:

  • 为什么在button 中使用div 元素?这根本不是正确的 HTML。 w3.org/TR/2012/WD-html5-20120329/… 很可能是这个问题。
  • 我不知道,为什么不呢? :) 包含非文本子项的按钮的正确标记是什么? &lt;div role="button"&gt;...&lt;/div&gt;?
  • @Red 打败了我。你可以只使用&lt;span&gt; 而不是&lt;div&gt;。或者不要使用button 作为包装器,而是使用具有类似按钮功能的 div

标签: css flexbox


【解决方案1】:

根据这个答案: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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 2019-02-18
    相关资源
    最近更新 更多