Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stack items above each other with flex box?

Tags:

html

css

flexbox

So I just googled a lot and was not able to find a solution for this. I want 2 items to be centered horizontally and vertically. The trick here is that I want to stack them above each other, no problem with position:absolute, but I can't center the elements with an absolute position. I think that this should work anyhow with flexbox. With stacking I mean so that one element is hiding the other partially.

enter image description here

like image 334
TobiasW Avatar asked Jul 22 '15 09:07

TobiasW


People also ask

How do you put flex items on top of each other?

To display the items vertically, use flex-direction: column and the items will stack on top of one another in a column instead of side-by-side in a row. "and positions it relative to it's closest positioned parent" - this would be true if parent's position was anything but default(static).

How do you stack elements on top of each other?

Using CSS position property: The position: absolute; property is used to position any element at the absolute position and this property can be used to stack elements on top of each other. Using this, any element can be positioned anywhere regardless of the position of other elements.

Can you have 2 Flex boxes?

Yes, that is absolutely fine. An element can be a flex child/item, and a flex container at the same time. You can use it, I post a working example .


2 Answers

The container can be set align-items: center and justify-content: center for horizontal and vertical centering.

.outer {
  align-items: center;
  background: #800000 none repeat scroll 0 0;
  border: 5px solid #353535;
  border-radius: 50%;
  display: flex;
  height: 300px;
  justify-content: center;
  position: relative;
  width: 300px;
}
.inner {
  background: #C83737;
  border: 5px solid #353535;
  width: 150px;
  height: 150px;
  border-radius: 50%;
}
<div class="outer">
  <div class="inner"></div>
</div>
like image 186
m4n0 Avatar answered Sep 20 '22 15:09

m4n0


Maybe something like this? fiddle

<div class="container">
    <div class="item"></div>
    <div class="item"></div>
</div>

.container {
    display: flex;
    flex-flow: wrap;
    align-items: center;
    justify-content: center;
    border: 1px solid black;
    height: 500px;
    width: 100%;
    align-content: center;
}

.item {
    flex: 1 100%;
    border: 1px solid black;
    height: 100px;
}
like image 45
Mimetix Avatar answered Sep 21 '22 15:09

Mimetix