0

I am trying to use horizontal flex elements inside a button, but they don't stretch vertically to the button height. Why?

Here is the snippet with button markup (does not 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>

Here is the snippet with div markup (does 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>

I also tried height: 100% oir self-align: stretch in .content class, without success.

Pandaiolo
  • 11,165
  • 5
  • 38
  • 70
  • 1
    Why are you using `div` elements inside a `button`? That's not correct HTML at all. https://www.w3.org/TR/2012/WD-html5-20120329/the-button-element.html#the-button-element Most likely that this is the problem. – Red Dec 19 '19 at 13:51
  • I did not know, why wouldn't I? :) What is the correct markup for button containing non-text children? `
    ...
    `?
    – Pandaiolo Dec 19 '19 at 13:55
  • @Red beat me to it. you can just have `` instead of `
    `. Or don't use `button` as a wrapper but a div with button-like functionalities
    – Cornel Raiu Dec 19 '19 at 13:57

1 Answers1

1

According to this answer: Flexbox not working on button or fieldset elements, in some browsers you can't set the display property of a button to anything else than block or inline-block.

The proposed solution is to add a wrapper:

(Note: as was already commented, a div inside a button is not correct HTML... Considder replacing it for span's.)

.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>
JasperZelf
  • 2,731
  • 1
  • 22
  • 34