Search code examples
htmlcssflexboxstylingmarkup

Make <div> same length and appear in column


I have the following structure

<!DOCTYPE html>
<html>

  <head>
    <title></title>
  </head>

  <body>
    <div id='whatStyling'>
      <div class='container'>
        <div class='element'>
          <p class='text'>Foo</p>
        </div>
      </div>
      <div class='container'>
        <div class='element'>
          <p class='text'>Bar</p>
        </div>
      </div>
      <div class='container'>
        <div class='element'>
          <p class='text'>Fooooooo Baaaaaar</p>
        </div>
      </div>
    </div>
  </body>

</html>

Mark Up

#whatStyling {
  display: flex;
  flex-direction: column,
}

.container {
  display: flex;
}

.element {
  display: flex;
  padding: 0.2rem 2.8rem 0.2rem 0.8rem;
  min-width: 1rem;
  background-color: rgb(255, 0, 0);
}

.text {
  color: rgb(128, 128, 128);
  font-family: Roboto, sans-serif;
  font-weight: 500;
  font-size: 1.5rem;
  background-color: rgb(255, 255, 255);
}

http://jsfiddle.net/g8ansow3/6/

I want to have all elements the same width, namely as wide as the longest "box" is (Fooooooo Baaaaaar) and appear as column. Note that I need the display: flex; on each .container. I further do not know how many elements there will be.

What styling would my most outer div #whatStyling need, if possible, with flex box.


Solution

  • Use inline-flex instead of flex then add width:100%

    #whatStyling {
      display: inline-flex; /*Changed this*/
      flex-direction: column; /* Corrected a typo here*/
    }
    
    .container {
      display: flex;
    }
    
    .element {
      display: flex;
      padding: 0.2rem 2.8rem 0.2rem 0.8rem;
      min-width: 1rem;
      width:100%; /*Added this */
      background-color: rgb(255, 0, 0);
    }
    
    .text {
      color: rgb(128, 128, 128);
      font-family: Roboto, sans-serif;
      font-weight: 500;
      font-size: 1.5rem;
      background-color: rgb(255, 255, 255);
    }
    <div id='whatStyling'>
      <div class='container'>
        <div class='element'>
          <p class='text'>Foo</p>
        </div>
      </div>
      <div class='container'>
        <div class='element'>
          <p class='text'>Bar</p>
        </div>
      </div>
      <div class='container'>
        <div class='element'>
          <p class='text'>Fooooooo Baaaaaar</p>
        </div>
      </div>
    </div>