Search code examples
htmlcssflexboxcentering

Displaying flexbox centered but align items left like text align left


I am trying to setup these divs to display in the centre but keep their items displayed left, like text-align: left would do.

Here's my example: https://jsfiddle.net/gr5Lmos1/

#donateList {
  display: flex;
  justify-content: center;
  align-items: center;
  align-self: center;
  flex-direction: column;
  flex-wrap: wrap;
}

.donateItem {
  flex: 0 1 auto;
  align-items: flex-start;
  justify-content: flex-start;
  align-self: center;
}

.donateItem * {
  display: inline-block;
}

.donateItem p {
  vertical-align: bottom;
}

.donateItem img {
  height: 64px;
  width: 64px;
}
<div id="donateList">
  <div class="donateItem">
    <img src="/images/icons/bitcoin.png">
    <p>Bitcoin:</p>
    <p>fkewjhf;eiwhf;iewfhwehfewifhew</p>
  </div>
  <div class="donateItem">
    <img src="/images/icons/paypal.png">
    <p>Paypal:</p>
    <p>eijfhewfwifhefefewf</p>
  </div>
</div>

I am trying to get the donateItem's contents to all display left but keep all the donateItem's divs centre as they are now.


Solution

  • If you are open to include another wrapper in your markup, it is easy:

    1. Use align-items: flex-start (or let it take the default stretch value) for the #donateList

    2. Center align vertically and horizontally the new wrapper div.

    See demo below (also removed some redundant styles):

    main { /* ADDED */
      display: flex;
      align-items: center;
      justify-content: center;
    }
    #donateList {
      display: flex;
      justify-content: center;
      align-items: flex-start; /* CHANGED */
      /*align-self: center;*/
      flex-direction: column;
      flex-wrap: wrap;
    }
    
    .donateItem {
      flex: 0 1 auto;
      /*align-items: flex-start;
      justify-content: flex-start;
      align-self: center;*/
    }
    
    .donateItem * {
      display: inline-block;
    }
    
    .donateItem p {
      vertical-align: bottom;
    }
    
    .donateItem img{
      height: 64px;
      width: 64px;
    }
    <main>
      <div id="donateList">
        <div class="donateItem">
          <img src="http://placehold.it/100x100">
          <p>Bitcoin:</p>
          <p>fkewjhf;eiwhf;iewfhwehfewifhew</p>
        </div>
        <div class="donateItem">
          <img src="http://placehold.it/100x100">
          <p>Paypal:</p>
          <p>eijfhewfwifhefefewf</p>
        </div>
      </div>
    </main>