June 22, 2011

How can I ensure two floated items stay side-by-side even if there isn’t enough width for both of them?

Question by David H

I have the following HTML:

<div  >
  <div >
    <div style="float: left;">
      <input type="checkbox" value="False" />
    </div>
    <div style="float: left;" >         XXXXXXXXXXXXXXXXXXXXXXXXXXXXX </div>
  </div>
</div>

It displays the XXX to the right of the checkbox. However, if I reduce the screen width, the XXX goes under the checkbox.

Is there any way that I can “lock” the XXX text inside the DIV so the XXXX always appears to the right and on the same line?

(Note that I want to keep using DIV as later on I do some jQuery things with the DIVs.)

Answer by Starx

That is what float:left is supposed to do. It will remain in the left side as much as possible. If the element before is also floated to the left side, it will try to float to left, together with it, if the space is available. That’s why when you resize your screen and there is not enought space for the div to float to the together with previous element, it will float to the left, down the previous element.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!