Search code examples
htmlcsscss-floatalignment

Floating text to the right affecting the container's width (no constant sizes)


Suppose I have the following UI:

<div>
    <span class="normal">text</span>
    <span class="pull-right">blah</span>
</div>

and style:

.pull-right {
    float: right;
    /* What should I put here to make "blah" appear on the same line as text? */
}
div {
    float: left; /* for wrapping the contents */
    border: 1px solid green; /* to help see the bounds */
}
.normal {
    border: 1px solid blue; /* to help see the bounds */
}

Actual result: When displayed in a browser (Chrome in my case) the blah is displayed below and to the right of text and the div is almost as wide as the two texts.

That's almost what I want.

Expected result: I want blah to be displayed to the right of text in the same line and the div (green box) to have the width of text and blah's width added together (without specifying any specific width values.

Here's a fiddle with the above minimal example and the original context where I have the same problem: http://jsfiddle.net/TWiStErRob/5TruW/

How should I style blah to make it work as expected?


Solution

  • Put the floated element before the text element.

    If you think about it, the HTML processes the elements in order. So it writes the text span and then it writes the floated span. There is no way for it to move them the way you want. Float elements must come before the elements wrapping them.