I am trying to achieve a HTML layout where items are aligned left/center/right regardless of their variable widths:
[[left with variable width] [centered in parent] [right]]
I have tried to implement this using "flexbox":
#left{background-color:aqua;}
#center{background-color:lime;}
#right{background-color:yellow;}
#box {background-color:gray;
margin: auto;
width: 30em;
display:flex;
}
/*attempt one
-> "center" pushed towards "right" by "left"
*/
#box{justify-content: space-between;}
/*attempt two
-> items assume same width, each content is left-aligned;
"left" wraps/expands along cross-axis (height)
*/
/*#left,#center,#right{flex: 1;}*/
/*attempt three
-> all items centered with minimum width
*/
/*
#box{justify-content: center ;}
*/
/* align-items / align-self is for cross-axis */
<div id="box">
<div id="left">left expands and pushes center</div>
<div id="center">center</div>
<div id="right">right</div>
</div>
but so far failed to create a simple solution. It probably is possible to use flexbox to create equal columns and then align each content left/center/right with additional containers or style rules.
Other questions have not yet solved my problem, such as Aligning three elements (left/center/right) inside a container, which also uses flexbox, but requires same-width elements.
How to align three divs (left/center/right) for getting in small screen left/right and under them center element uses float as an alternative.
The excellent In CSS Flexbox, why are there no "justify-items" and "justify-self" properties? shows a few solutions, on of which uses absolute positioning for the center item and margin:auto;
for the right item.
It seems, that without justify-self
for flexbox, my goal cannot be realized.
gridlayout (which has justify-self) may be an alternative:
#box{
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
#left{justify-self:flex-start;}
#center{justify-self:center;}
#right{justify-self:flex-end;}
But I might be wrong, so the the questions remaining are:
- can flexbox solve this "cleanly" (without additional child containers/rules)?
- what would be a solution with additional rules (text-align?)
- do I need to turn to floats or gridlayout?