How can I ensure two floated items stay side-by-side even if there isn’t enough width for both of them?
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开发者_如何学C 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.)
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/
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>
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.
精彩评论