mikemaccana
mikemaccana

Reputation: 123440

display: table-cell centering with two elements, rather than three

I have a working example of vertically centering elements of unknown height, using three elements:

<section>
    <div>
        <img src="http://placehold.it/100x100"/>
    </div>
</section>​

And the CSS:

section {
  display: table;
  width: 100%;
  height: 100%;
  position: absolute;
  text-align: center;
}

div {
  display: table-cell;
  vertical-align: middle;
}

There's also a JSFiddle example here: http://jsfiddle.net/Y6KS9/

However I'd like to avoid using unnecessary wrappers if possible. Eg, having the img itself display as table-cell:

div {
  display: table;
  width: 100%;
  height: 100%;
  position: absolute;
  text-align: center;
}

img {
  display: table-cell;
  vertical-align: middle;
}
​

However this doesn't work - see the JSFiddle example at http://jsfiddle.net/U2c9R/ - the img is not centered within the div.

Is it possible to vertically center an image of unknown size within its parent using only two elements?

Edit: I'm aware of Flexbox, and intending to throw out the table cell hack completely once IE9 dies. But right now I need to support old browsers.

Upvotes: 1

Views: 152

Answers (1)

gearsdigital
gearsdigital

Reputation: 14225

You could try to use the CSS3 Flexible Box Model.

You should check the browser availability. As you can see by the -webkit vendor prefix my Example currently works only in -webkit-based render engines. But i'm pretty sure it'll work in most modern browsers.

Here is an overview of browsers which supporting the Flexible Box Model: http://caniuse.com/#feat=flexbox

div {
    display: -webkit-box;
    -webkit-box-pack: center;
    -webkit-box-align: center;
    height:100%;
    width:100%;
    position:absolute;
}

Example: http://jsfiddle.net/U2c9R/4/

Update

For Cross-browser support for the CSS3 Flexible Box Model you could use Modernizr and a proper Polyfill which adds support for IE 6-9 and Opera 10.0+. The only hint is, this wouldn't work without JavaScript. But maybe this is an option?

Upvotes: 1

Related Questions