Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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.)

like image 400
David H Avatar asked Jun 22 '11 09:06

David H


People also ask

How do you float elements side by side?

Use CSS property to set the height and width of div and use display property to place div in side-by-side format. float:left; This property is used for those elements(div) that will float on left side. float:right; This property is used for those elements(div) that will float on right side.

How do I put two containers side by side?

The most common way to place two divs side by side is by using inline-block css property. The inline-block property on the parent placed the two divs side by side and as this is inline-block the text-align feature worked here just like an inline element does.

How do I make two sections side by side in HTML?

To position the divs side by side, we are using the float property to float each . float-child element to the left. Since they are both floating to the left, they will display side by side if there's enough space for both to fit. They do fit because we have two .

How do I display list items side by side in HTML?

The first way you can use is the display: inline-block method. This method is a simple and classic CSS technique for positioning elements side by side.


2 Answers

If you want them to always be on the same line, you can reasonably combine the two divs into one, still floated, and use the white-space property to keep it on one line:

<div>
  <div>
    <div style="float:left; white-space:nowrap;">
      <input type="checkbox" value="false" />         XXXXXXXXXXXXXXXXXXXXXXX 
    </div>
  </div>
</div>

Starx's answer explains very well why it's not really feasible to do this with two separate floated divs.

edit: http://jsfiddle.net/nkorth/qQSCV/

like image 133
nkorth Avatar answered Nov 15 '22 08:11

nkorth


yep, you can do that by setting fixed width for the container, like so:

<div>
  <div style="width:400px">
    <div style="float: left;">
      <input type="checkbox" value="False" />
    </div>
    <div style="float: left;" >         XXXXXXXXXXXXXXXXXXXXXXXXXXXXX </div>
  </div>
</div>
like image 21
Ruslan Avatar answered Nov 15 '22 07:11

Ruslan