Wolfgang Adamec
Wolfgang Adamec

Reputation: 8544

css, float alternative

In my web app I have a toolbar, it's a div:

The div has 3 spans. The contents of the 3 spans get filled later.

And the size of the individual spans differ every time.

<div>
    <span id="ab1" style="display: inline-block;"></span>
    <span id="ab2" style="display: inline-block;"></span>
    <span id="ab3" style="display: inline-block;"></span>
</div>

Now, I want, that span "ab1" should be placed on the left, "ab2" and "ab3" on the right side on the div.

Is this possibe WITHOUT float right/left?

Upvotes: 15

Views: 65541

Answers (3)

bhv
bhv

Reputation: 5398

Add display:flex to the parent element and margin-left:auto to any child element.
(that child element and all the next child elements float to right)

div {
  display: flex;
  border: 1px solid green;
}

span {
  border: 2px solid red;
}

#ab2 {
  margin-left: auto; /* this and the next elements float to right */
}
<div>
  <span id="ab1">sometext 1</span>
  <span id="ab2">sometext 2</span>
  <span id="ab3">sometext 3</span>
</div>


Or to display only one element to a side, add higher order to that element

div {
  display: flex;
  border: 1px solid green;
}

span {
  border: 2px solid red;
}

#ab2 {
  margin-left: auto;
  order: 1; /* this becomes the last element, only this element float to right */
}
<div>
  <span id="ab1">sometext 1</span>
  <span id="ab2">sometext 2</span>
  <span id="ab3">sometext 3</span>
</div>

Upvotes: 5

Sowmya
Sowmya

Reputation: 26989

Use position:absolute and text-align:right

CSS

div{background:red; text-align:right; position:relative;}
#ab1{position:absolute; left:0; background:yellow;}
#ab2{background:yellow;}
#ab3{background:yellow;}

DEMO

Upvotes: 13

Asad
Asad

Reputation: 131

You can use display flex for container and margin-left: auto for #ab2.

div{
    display: flex;
}
#ab2{
    margin-left: auto;
}

Upvotes: 13

Related Questions