2

I'd like to display a button with an image and text. The text and image must be centered and on the same row/line.

In Firefox the image and text are always on separate lines. How can I solve this?

This is what I've got:

button {
    display: inline-flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: center;
    align-content: stretch;
    align-items: center;
}

button img {
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
}

button span {
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
}

JsFiddle

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
NinjaFart
  • 1,626
  • 1
  • 20
  • 24

2 Answers2

7

Certain HTML elements, by design, do not accept display changes. Three of these elements are:

  • <button>
  • <fieldset>
  • <legend>

For instance, display: table won't work on fieldset.

Similarly, applying display: inline-flex to button will be ignored by the browser.

There are other sensible restrictions. For instance, some browsers will ignore overflow: scroll on button elements. (Tested: Firefox, no scroll; Chrome, yes)

So, bottom line, a button element cannot be a flex container.

The easy fix is to wrap the content of the button in a div, and make the div the flex container. Or (as mentioned in the comments) use a span instead of a div, as this maintains standards compliance.

HTML

<button href="#">
    <div>
        <img src="http://placehold.it/10x10">
        <span>Click me</span>
    </div>
</button>

CSS

div {
    display: flex;
    justify-content: center;
    align-items: center;
    }

DEMO

NOTE: Although they cannot be flex containers, button elements can be flex items.

Learn more here:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    Perfect. Div's inside buttons isn't W3 valid, so I've changed it to a span: https://jsfiddle.net/tr55t9c5/6/ - Also, I see there are other solutions, but in my case i really needed the flex-box feature to more easily control the height of the button. – NinjaFart Oct 26 '15 at 13:25
-1

demo:https://jsfiddle.net/tr55t9c5/3/

remove all the css and just add this css only.

    button {text-align:center;}
ItzMe_Ezhil
  • 1,276
  • 2
  • 11
  • 22