Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positioning adjacent elements

I'm trying to achieve the following effect:

+----------------------+-----------------------------------+-----------------------+
| span (absolute left) | div consuming all space inbetween | span (absolute right) |
+----------------------+-----------------------------------+-----------------------+

On the surface it feels really straightforward; however:

  • I don't want to set the width of the left/right elements (I want them to 'shrink-wrap' automatically); and
  • I don't want to set the width of the all-consuming div (I want it to fill the arbitrary space).

I have been fiddling with relative positioning and floats for a while and am beginning to feel like I'm missing something obvious, since I'm so close. I'd be grateful to be put out of my misery :)

(Using a table just occurred to me - I'll have another fiddle meanwhile.)

Thanks :)

like image 266
c24w Avatar asked Apr 01 '26 11:04

c24w


1 Answers

Thanks bPratik! I had an epiphany when I read: floated columns begin "floating" at the point in the parent element's text where they first appear.

The principle code I had was correct:

<div>
    <span style="float:left">span (float left)</span>
    <div>greedy div</div>
    <span style="float:right">span (float right)</span>
</div>

However, that creates the following:

+-------------------+--------------------------+--------------------+
| span (float left) |                  greedy div                   |
+-------------------+--------------------------+--------------------+
                                               | span (float right) |
                                               +--------------------+

Therefore, the order of elements has to be span, span, div, otherwise the right-floating span is forced onto the line beneath (by the greedy div stealing it's spot).

Hence, the solution:

<div>
    <span style="float:left">span (float left)</span>
    <span style="float:right">span (float right)</span>
    <div>greedy div</div>
</div>

And subsequent result:

+-------------------+--------------------------+--------------------+
| span (float left) |        greedy div        | span (float right) |
+-------------------+--------------------------+--------------------+

I hope that's clear :)

like image 200
c24w Avatar answered Apr 04 '26 06:04

c24w



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!