Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 732
Xavi Avatar asked May 26 '13 10:05

Xavi


1 Answers

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.

like image 124
cimmanon Avatar answered Sep 30 '22 20:09

cimmanon