我想在同一行上使用float: left表示左边的项。

我一个人做到这一点没有问题。问题是,我希望这两个项目保持在同一行,即使您将浏览器调整到非常小。你知道的…就像桌子一样。

这样做的目的是让右边的物品无论如何都不会被包装。

我如何使用CSS告诉浏览器,我宁愿拉伸包含的div而不是包装它,所以float:右;Div在float的下面:left;div吗?

我想要的是:

                                   \
 +---------------+  +------------------------/
 | float: left;  |  | float: right;          \
 |               |  |                        /
 |               |  |content stretching      \   Screen Edge
 |               |  |the div off the screen  /  <---
 +---------------+  +------------------------\
                                             /

当前回答

我解决这个问题的方法是使用一些jQuery。我这样做的原因是因为A和B是宽度的百分比。

HTML:

<div class="floatNoWrap">
    <div id="A" style="float: left;">
        Content A
    </div>
    <div id="B" style="float: left;">
        Content B
    </div>
    <div style="clear: both;"></div>
</div>

CSS:

.floatNoWrap
{
    width: 100%;
    height: 100%;
}

jQuery:

$("[class~='floatNoWrap']").each(function () {
    $(this).css("width", $(this).outerWidth());
});

其他回答

解决方案1: 显示:table-cell(不广泛支持) 解决方案2: 表 (我讨厌黑客。)

When user reduces window size horizontally and this causes floats to stack vertically, remove the floats and on the second div (that was a float) use margin-top: -123px (your value) and margin-left: 444px (your value) to position the divs as they appeared with floats. When done this way, when the window narrows, the right-side div stays in place and disappears when page is too narrow to include it. ... which (to me) is better than having the right-side div "jump" down below the left-side div when the browser window is narrowed by the user.

用最小宽度大于浮动体的组合宽度+边距的div包装浮动体。

不需要黑客或HTML表格。

另一个选择是,不使用浮动,而是将空白属性nowrap设置为父div:

.parent {
     white-space: nowrap;
}

并重置空白和使用内联块显示,这样div保持在同一行,但你仍然可以给它一个宽度。

.child {
    display:inline-block;
    width:300px;
    white-space: normal;
}

这是一个JSFiddle: https://jsfiddle.net/9g8ud31o/

你确定浮动块级元素是这个问题的最佳解决方案吗?

在我的经验中,经常遇到CSS困难,结果证明我看不到做我想做的事情的方法的原因是我陷入了关于我的标记的隧道视野(思考“我如何让这些元素做到这一点?”)而不是回头看看我到底需要实现什么,可能会稍微重做我的html来促进它。