Is it possible to use the flex layout to center an absolutely positioned element?

Xavi picture Xavi · May 26, 2013 · Viewed 10.5k times · Source

The CSS3 flexbox, or flex, layout allows to easily center an element horizontally and vertically even when its height and width are unknown.

Can the flex layout be used to absolutely position an overlay (of unknown height and width) in the center of a page?

Answer

cimmanon picture cimmanon · May 26, 2013

Elements lose their flex item status if they are absolutely positioned. In order to do what you're suggesting, you need to absolutely position the flex container:

http://codepen.io/cimmanon/pen/prFdm

.foo {
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.bar {
  margin: auto;
}

<div class="foo">
  <div class="bar">Bar</div>
</div>

Note that I've omitted the moz 2009 Flexbox prefixes because absolute positioning breaks flex containers in Firefox. It should just work in Firefox versions with the standard Flexbox properties.