0

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?
handle
  • 5,859
  • 3
  • 54
  • 82
  • 1
    possible duplicate of: https://stackoverflow.com/a/55393886/8620333 ( you will need extra containers) – Temani Afif Mar 07 '20 at 10:20
  • ^ if the duplicate is suitable for you I can close the question if you want – Temani Afif Mar 07 '20 at 10:54
  • @TemaniAfif If offers one solution, but not all the answers. However, feel free to close, as my question really is quite the same. – handle Mar 07 '20 at 11:13
  • An old question, lots of `float` solutions: https://stackoverflow.com/questions/2603700/how-to-align-3-divs-left-center-right-inside-another-div – handle Mar 07 '20 at 11:21

0 Answers0