I'm trying to center an image in a flexbox container (see the exact code below). It has to do the following:

  • center image horizontally
  • center image vertically
  • downscale image to 90% container width or height if needed

The problem, however, is that firefox (v27) is acting as if the image is always 90% width and height. Chrome and mobile browsers seem to render this the way i want.

<div class="flex-cc">
    <img src="image/url/" alt="" />
</div>

Fiddle: http://jsfiddle.net/f4fg5/1/

Is there any way to overcome this firefox behaviour?

UPDATE There is an answer to this question, but it provides an alternative way rather than solving flexbox issues. If you're looking to center and fit an image in a container, have a look at the accepted answer.

有帮助吗?

解决方案

I'm going to advise dropping using Flexbox for this purpose, since trying to scale images has unexpected results in some browsers.

There is very compact alternate method for vertical centering that has an added bonus of working in IE9 (prefixes may be necessary):

http://jsfiddle.net/f4fg5/6/

.flex-cc {
    float: left;
    height: 150px;
    margin-bottom: 10px;
    margin-right: 10px;
    width: 150px;
    background: yellow;
}
.flex-cc img {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
    max-height: 90%;
    max-width: 90%;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

其他提示

I might have found an answer to this question:

Setting width: -moz-available on the img element will almost fix it, it's supported from firefox 31.

https://developer.mozilla.org/de/docs/Web/CSS/width

Updated jsfiddle:

http://jsfiddle.net/f4fg5/10/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top