html - 为什么所有内容都在嵌套在 float 或内联 block 元素内的绝对元素内自动换行

标签 html css

我有这部分样式,一个相对内联 block 元素,里面有一个绝对元素:

<div style="display:inline-block;position: relative">
  <div style="position:absolute">
    <input type="text" />
    <input type="button" value="submit" />
  </div>
</div>

一种情况也不太不寻常,可以在 CSS 下拉菜单中看到,但不是使用 float:leftli 元素,而是使用 display :内联 block

为什么在这种特定情况下,绝对 block 内的输入被换行?而且,如果您尝试删除分配的属性之一(从位置到显示),它不会突然换行吗?以及如何在不改变样式结构的情况下解决?

<div style="display:inline-block;position: relative">
  <div style="position:absolute">
    <input type="text" />
    <input type="button" value="submit" />
  </div>
</div>

最佳答案

具有position:absolute 的元素具有收缩以适合 行为。如果你写一个长句子,你会注意到同样的想法,它会在每个单词上中断:

<div style="display:inline-block;position: relative">
  <div style="position:absolute">
    aaaa bbb ccc ddd  eee fff
  </div>
</div>

来自 the specification :

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, calculate the available width: this is found by solving for 'width' after setting 'left' (in case 1) or 'right' (in case 3) to 0.

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

在这种情况下,可用宽度 将为 0,因为包含 block 是 inline-block(它的宽度为 0,因为它唯一的子元素已从流中删除) , 所以 max 将是首选的最小宽度 并且首选的宽度 肯定会更大因此我们将以首选的结束最小宽度


删除 inline-blockposition:relative 将改变包含 block 的宽度或包含 block 因此可用宽度将更改,它将被选中而不是首选的最小宽度,因为在这两种情况下我们都将以 block 元素作为包含 block 结束。

使用 float:left 而不是 inline-block 将创建相同的输出,因为 float 的宽度也等于 0:

<div style="float:left;position: relative">
  <div style="position:absolute">
    aaaa bbb ccc ddd  eee fff
  </div>
</div>

避免这种情况的一种简单方法是使用 white-space:nowrap 来避免所有可能的换行符,首选最小宽度 将简单地等于 首选宽度。

<div style="float:left;position: relative">
  <div style="position:absolute,white-space:nowrap;">
    aaaa bbb ccc ddd  eee fff
  </div>
</div>

关于html - 为什么所有内容都在嵌套在 float 或内联 block 元素内的绝对元素内自动换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54346873/

相关文章:

css - 使用位置 :absolute inside relative can create problems in Print , 屏幕阅读器和移动用户?

javascript - 如何隐藏样式属性?

javascript - 显示 : block error - Keep blinking

javascript - 如何创建<a download>而不点击?

javascript - 如何仅在用户第一次滚动到某个元素时运行自定义函数?

css - 下面的 css 选择器有什么区别

html - 当存在 <br> 时,如何文本对齐 div 的最后一行?

html - 媒体查询 : Three external CSS files

javascript - 当这些样式移入 .CSS 文件时,直接应用于元素的样式将丢失

javascript - 单击 div 滚动到 div