Below are five options for achieving this layout:
- CSS Positioning
- Flexbox with Invisible DOM Element
- Flexbox with Invisible Pseudo-Element
- Flexbox with
flex: 1
- CSS Grid Layout
Method #1: CSS Positioning Properties
Apply position: relative
to the flex container.
Apply position: absolute
to the green flex item.
Now the green square is absolutely positioned within the flex container.
More specifically, the green square is removed from the document flow but stays within the bounds of the nearest positioned ancestor.
Use the CSS offset properties top
, bottom
, left
and right
to move the green square around.
flex-container {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: nowrap;
position: relative;
border: 4px solid blue;
height: 300px;
width: 300px;
}
flex-container > flex-item:first-child {
display: flex;
}
flex-container > flex-item:first-child > flex-item {
border: 4px solid aqua;
height: 50px;
width: 50px;
margin: 0 5px;
}
flex-container > flex-item:last-child {
position: absolute;
bottom: 40px;
left: 50%;
transform: translateX(-50%); /* fine tune horizontal centering */
border: 4px solid chartreuse;
height: 50px;
width: 50px;
}
<flex-container>
<flex-item><!-- also flex container -->
<flex-item></flex-item>
<flex-item></flex-item>
<flex-item></flex-item>
</flex-item>
<flex-item></flex-item>
</flex-container>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…