In order to perfectly center the #center
element in the flex container, while having another element at the top, there are two ways you could do this:
- Introduce a third ("phantom") element to create equal balance, or
- Absolutely position the
#center
element.
(These same methods could be used to center one item and fix another element to the bottom.)
It would be easy to center the #center
element if it were the only flex item in the container. Either of the following two methods would suffice:
#wrap {
display: flex;
justify-content: center;
align-items: center;
}
OR
#center {
margin: auto;
}
Except there is a second flex item in the container occupying space at the top. This means that the centering methods above – which are based on the distribution of free space in the container – won't be precise. They will center the #center
element inside the remaining space, but not inside the entire space (because #top
is occupying space which, as a result, is excluded from the calculation).
In the following demo, #center
is perfectly centered in the gray area, but not in the entire flex container, which includes the orange area:
DEMO 1
The #center
element looks centered, and that may be enough for your purposes, but it's not precisely centered. It's off vertically by 50px, which is the height of the #top
element.
So another centering method must be used that takes the #top
space into consideration.
Method #1: Introduce a third "phantom" element for equal balance
This method involves creating a third flex item with the same height as #top
. We place this new item on the other side of #center
to create an equal balance of space on both sides. We then hide this item with visibility: hidden
.
HTML
<div id="wrap">
<div id="top"></div>
<div id="center"></div>
<div id="bottom"></div><!-- invisible flex item -->
</div>
CSS (relevant section)
#top {
flex: 0 0 50px;
width: 100%;
background-color: orange;
}
#center {
margin: auto;
width: 200px;
height: 300px;
background-color: aqua;
}
#bottom {
flex: 0 1 50px;
visibility: hidden;
}
Now #center
is perfectly centered in the flex container.
DEMO 2
Method #2: Absolutely position the `#center` element
Flexbox allows for the absolute positioning of flex items. This means we could remove #center
from the document flow and position it relative to its parent.
HTML
<div id="wrap">
<div id="top"></div>
<div id="center"></div>
</div>
CSS (relevant sections)
#wrap {
position: relative;
}
#center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Although this method doesn't require an extra flex item (like in Method #1) – and still achieves perfect centering – by removing this item from the document flow it can overlap other elements.
DEMO 3