html - 为什么应用 css 宽度会导致此框下降一行?

标签 html css css-float

我意识到这个问题很具体...我试图弄清楚“宽度”对 css 盒模型的影响。

我在两个单选按钮的左侧有一个标签。标签向左浮动,单选按钮出现在标签的右侧。单选按钮本身在其右侧有标签,这些标签可以很长。

radio 位于 UL block 中。

当我有 width:auto;在 UL block 上,然后将浏览器缩小到相当窄,单选按钮及其各自的标签会下拉到下一行。

如果我删除 width:auto,单选按钮保持 float ,单选按钮旁边的标签字符串继续收缩,这正是我想要的。

我的问题是:为什么 width:auto 会导致 radio 及其标签下降一行?是因为 width:auto 试图创建一个框来容纳标签字符串的全长而不流动文本吗?还是有其他因素在起作用?

这是演示行为的示例代码:

<style>
    .inlineLabels ul{
        float:left;
        width: 66%;
        padding: 0;
    }

    p.label{
        float:left;
        text-align:right;
        position:relative;
        width:32%;
        margin: .3em 2% 0 0;
        display:block;
    }

    ul.blockLabels{
        /*width:auto; why does uncommenting this cause the radios to drop down to a new line when shrinking browser size? */ 
        list-style:none;
    }
</style>
<fieldset class="inlineLabels">
    <div>
        <p class="label">Choose:</p>
        <ul class="blockLabels">
            <li>
                <label for="a-1">
                    <input name="a" id="a-1" value="0" type="radio">&nbsp;<span class="">A short string</span>
                </label>
            </li>
            <li>
                <label for="a-2">
                    <input name="a" id="a-2" value="1" type="radio">&nbsp;<span class="">A very very very  very very very very very very  very very very string</span>
                </label>
            </li>
        </ul>
    </div>
</fieldset>

最佳答案

TLDR:宽度为 auto 的 float 元素的“首选宽度”是没有换行符的内容的宽度。这就是为什么引擎会首先包装 float ,并且仅作为最后一项措施,它才会开始在 float 内包装文本。

您可以在规范中阅读答案:http://www.w3.org/TR/CSS2/visudet.html#float-width

If 'width' is computed as 'auto', the used value is the "shrink-to-fit" width.

Calculation of the shrink-to-fit width is similar to calculating the width of a table cell using the automatic table layout algorithm. Roughly: calculate the preferred width by formatting the content without breaking lines other than where explicit line breaks occur, and also calculate the preferred minimum width, e.g., by trying all possible line breaks. CSS 2.1 does not define the exact algorithm. Thirdly, find the available width: in this case, this is the width of the containing block minus the used values of 'margin-left', 'border-left-width', 'padding-left', 'padding-right', 'border-right-width', 'margin-right', and the widths of any relevant scroll bars.

Then the shrink-to-fit width is: min(max(preferred minimum width, available width), preferred width).

关于html - 为什么应用 css 宽度会导致此框下降一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7851083/

相关文章:

css - 如何 - 右侧边框的 CSS 背景

javascript - 合并图像函数导致 iOS 上的混合应用程序结果不正确 - 适用于 Safari

javascript - 查找并分隔 JavaScript 字符串中的链接

html - 强制CSS样式属性使页面上的元素居中

javascript - jQuery 中的汉堡菜单

css - 在 div 中向左浮动在 IE7 中不起作用,但在 Firefox 和 IE8 中起作用

css - 混合 float 和绝对定位问题

html - CSS float 、溢出和绝对位置

html - 我的导航栏比子元素小

html - <table> 中的固定位置在 Firefox 和 Chrome 58 中不起作用