Making a flex item float right

HtmlCssFlexbox

Html Problem Overview


I have a

<div class="parent">
    <div class="child" style="float:right"> Ignore parent? </div>
    <div> another child </div>
</div>

The parent has

.parent {
    display: flex;
}

For my first child, I want to simply float the item to the right.

And my other divs to follow the flex rule set by the parent.

Is this something possible?

If not, how do I do a float: right under flex?

Html Solutions


Solution 1 - Html

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

.parent {
  display: flex;
}
.child {
  margin-left: auto;
  order: 2;
}

<div class="parent">
  <div class="child">Ignore parent?</div>
  <div>another child</div>
</div>

Solution 2 - Html

You don't need floats. In fact, they're useless because floats are ignored in flexbox.

You also don't need CSS positioning.

There are several flex methods available. auto margins have been mentioned in another answer.

Here are two other options:

  • Use justify-content: space-between and the order property.
  • Use justify-content: space-between and reverse the order of the divs.

.parent {
    display: flex;
    justify-content: space-between;
}

.parent:first-of-type > div:last-child { order: -1; }

p { background-color: #ddd;}

<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>

<div class="parent">
    <div class="child" style="float:right"> Ignore parent? </div>
    <div>another child </div>
</div>

<hr>

<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of 
             divs in the mark-up</p>

<div class="parent">
    <div>another child </div>
    <div class="child" style="float:right"> Ignore parent? </div>
</div>

Solution 3 - Html

Use justify-content: flex-end; in parent:

display: flex;
width: 100%;
flex-wrap: wrap;
justify-content: flex-end;

more info

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZhen LiuView Question on Stackoverflow
Solution 1 - HtmlNenad VracarView Answer on Stackoverflow
Solution 2 - HtmlMichael BenjaminView Answer on Stackoverflow
Solution 3 - HtmlEmir MamashovView Answer on Stackoverflow