Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 Flex: Pull child to the right

Tags:

html

css

here's what I have Fiddle

ul {    display: flex;    justify-content: flex-start;    flex-direction: row;    align-items: center;    width: 100%;    height: 100px;    background: #333;    padding: 15px;  }    ul li {    padding: 15px;    margin: 5px;    background: #efefef;    border: 1px solid #ccc;    display: inline-block;    list-style: none;  }    #item-1 {    height: 50px;  }    #item-2 {    height: 70px;  }
<ul>    <li id="item-1">Home</li>    <li id="item-2">Menu</li>    <li>More</li>    <li>Stuff</li>    <li>Settings</li>  </ul>

I want the last item inside the flex-box to be pulled to the right ("Settings" in my fiddle) while keeping all other items the way they are. The "Settings"-item should also be centered vertically and everything.

align-self: flex-end pushes the item to the bottom (I want it on the right).

I would very much prefer a solution using flex-box because my items have variable heights and should always be centered vertically.

What is the cleanest way to achieve this?

Thanks for your help!

like image 703
Macks Avatar asked Oct 24 '13 11:10

Macks


People also ask

How do you align a flex item to the right?

In simple words, flex-items now expand from right to left as shown in the given figure. When justify-content is set to “flex-end”, it instantly shifts all the flex-items to the end of the flex-container along the main-axis, i.e flex items get right aligned.

How do you position flex items?

Justify ContentFlex Start positions element at the start of the page. Flex End sets the element to the end of the page. Space Around arranges the items evenly but with spaces between them. The spaces will be equal among all the elements inside a flex-box container, but not outside them.

How do I align a single flex item?

If you do want to align one item, or split a group on the main axis, use auto margins to do so; The align-items property sets all of the align-self values as a group. Use align-self on the flex child to set the value for an individual item.


1 Answers

Simple fix, use an auto-adjusting margin:

ul li:last-child {     margin-left: auto; } 

You may also want to not use width: 100% so that the element stays inside the visible area:

ul {     display: flex;     justify-content: flex-start;     flex-direction: row;     align-items: center;     /* width: 100%; */     height: 100px;     background: #333;     padding: 15px; } 

http://jsfiddle.net/dwLHE/

See also https://www.w3.org/TR/css-flexbox-1/#auto-margins

like image 114
ndm Avatar answered Sep 20 '22 17:09

ndm