Search code examples
cssalignmentflexbox

Flexbox justify-content depending on number of children


Having this:

  <label>
    <button>Create</button>
  </label>

I want button to be aligned to the right like this

----------------------------
|                   [create]|
----------------------------

while having this:

  <label>
    <button>Delete</button>
    <button>Update</button>
  </label>

I want buttons to be in the corners

----------------------------
|[delete]          [update]|
----------------------------

Without adding additional classes to the label.


Solution

  • You can do this using nothing but standard flexbox properties:

    • flex-direction: row-reverse - put the items in a row, start from "the end" (depends on reading direction)
    • justify-content: space-between - put the items as far away from each other as possible

    label {
      display: flex;
      flex-direction: row-reverse;
      justify-content: space-between;
    }
    <label>
      <button>Create</button>
    </label>
    
    <label>
      <button>Delete</button>
      <button>Update</button>
    </label>