Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"display: flex" on <button> versus on <span>

Tags:

html

css

flexbox

I have a question about the calculation of the width of flex containers. The element seems to behave differently to other elements in this regard.

If I add the style "display: flex" to a <span> element containing text, it takes 100% of its parent's width.

If I add the same style to a <button> element, its width is calculated according to its textual content.

How is this so? Which (implicit) CSS rule on the <button> element generates this behaviour? And how can I switch between both behaviours?

(I've tested this in Firefox and in Chrome. I could as well have taken a <div> instead of a <span>.)

like image 941
Marc Avatar asked Oct 21 '25 14:10

Marc


1 Answers

display: flex works to an extent on buttons in webkit based browsers such as Chrome and Safari, though the behaviour of the button and its flex children is buggy. It does not work at all in Firefox, and this might be technically the correct behaviour — here is a related bug report.

If you want to use display: flex on a button, place the property on a child div. To have the button stretch to fit its parent, give it width: 100%;.

button {
  display: block;
  width: 100%;
  padding: 10px;
}
button > div {
  display: flex;
}
button > div > div {
  flex: 2;
  background: #F00;
}
button > div > div:first-child {
  background: #F90;
  flex: 1;
}
<button>
  <div>
    <div>Hello, I am button div 1</div>
    <div>Hello, I am button div 2</div>
  </div>
</button>
like image 139
misterManSam Avatar answered Oct 23 '25 04:10

misterManSam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!