Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pull items in flexbox?

Tags:

css

flexbox

I need to create a following structure:

|                                         |
| [item][item][item]          [item][item]|
|                                         |

There are 5 items inside. They are all vertically aligned to the middle. 3 first elements are pulled to the left and 2 last elements are pulled to the right.

I know I can use floats for it, but it has several drawbacks, including troublesome vertical aligning.

I decided to use flexbox, which turns out to be a lot more convenient and flexible. Plus, it's more responsive-friendly.

Now my question is, can I distribute my elements like this in flexbox? Ideally, each of those 5 elements would be flexbox item. But how can I tell flexbox to pull those 3 to the left and those 2 to the right? I think adding empty element to fill space is not the best idea.

Is this doable or do I need to do it like this?

|                                         |
| [      item      ]          [   item   ]|
|                                         |

Where each item would contain needed elements inside, or perhaps even be separate flexboxes?

like image 369
Robo Robok Avatar asked Dec 15 '22 12:12

Robo Robok


2 Answers

Use display: flex along with margin-left: auto for the 4th child element

<main>
  <div>item 1</div>
  <div>item 2</div>
  <div>item 3</div>
  <div>item 4</div>
  <div>item 5</div>
</main>

Css

main {
  display: flex; 
}

div {
   width: 12%;
   margin: 0 10px;
   border: 1px red solid;
}

div:nth-child(4) {
  margin-left: auto;
}

Codepen: http://codepen.io/anon/pen/wKvMOw


Output:

enter image description here

like image 130
Fabrizio Calderan Avatar answered Dec 17 '22 02:12

Fabrizio Calderan


Or you could stick w/ Flexbox Layout and let the flex prop do all the magic. Personally, I don't like setting margins (other than margin:0;) in a flex box layout, it can throw off the layout and also generate unwanted scroll bars.

<div class="rowNoWrap">
  <div class="flexyChild">[  item  ]</div>
  <div class="flexyChild">[  item  ]</div>
  <div class="flexyChild">[  item  ]</div>
  <div class="flexyChild">[  item  ]</div>
  <div class="flexyChild">[  item  ]</div>
</div>

.rowNoWrap {
    display: flex;
    display: -webkit-flex;
    -webkit-flex-flow: row nowrap;
    -moz-flex-flow: row nowrap;
    -ms-flex-flow: row nowrap;
    -o-flex-flow: row nowrap;
    flex-flow: row nowrap;
}
.flexyChild {
    flex: 1;
}
.flexyChild:nth-child(4) {
    flex: 5;
    text-align: right;
    padding-right: 2%;
}

Gives you this layout: enter image description here

jsFiddle here

like image 43
kevinB Avatar answered Dec 17 '22 02:12

kevinB