【问题标题】:Prevent absolute positioned element from dividing a word防止绝对定位元素分割单词
【发布时间】:2012-10-15 01:23:29
【问题描述】:

有没有办法防止空的绝对定位块元素导致自动换行?

我的 html 看起来像

    some other words here. 
My_very_long_text<div style='position: absolute; width:20px; height:20px; background-color:green;'></div>_This_should_Not_be_on_next_line

问题是浏览器会在 My_very_long_text 之后进行自动换行(将文本移动到下一行),以便 _This_should_Not_be_on_next_line 确实从下一行开始。有什么办法可以防止吗?

在这种情况下,解决方案将在“此处插入一些其他单词”的换行符,因此应该输出文本,就好像绝对定位的 div 不存在一样。

添加: 我添加了一个显示问题的测试用例。 (在 firefox 16.0.1 中测试,它在“My_very_long_text”之后换行。如果我启动 firebug 并删除绝对定位的跨度,那么文本会按预期中断。但我只是在 chrome 中对其进行了测试,它可以按预期工作,所以也许这只是一个 Firefox 错误。

<!DOCTYPE HTML>
<html>
<head></head>
<body>
<div style='width:600px; background-color:red; position:relative; font-size:14px; font-family: monospace'>
so much better to test it this way My_very_long_text<span style='position: absolute; width:20px; height:20px; background-color:green;'></span>_This_should_Not_be_on_next_line
</div>
</body>
</html>

【问题讨论】:

  • 作为 bookcasey cmets,这应该不是问题,你能把整个页面贴出来看看你的问题吗?
  • 同意。它可能只是一个 Firefox 错误

标签: html css word-wrap


【解决方案1】:

绝对位置元素对文档的常规流程没有影响。绝对定位的元素不会“推动”其他元素,它们存在于自己的平面上。其他原因导致自动换行。

【讨论】:

  • Se 更新了显示问题的案例。可能是 Firefox 中的错误?
  • 很遗憾我不能同意。我的意思是他们应该这样做,但他们不会,至少在 Webkit 上不会。我现在有这个问题:一个复选框和一个关联的标签。提交后我验证,并且绝对定位的 div 出现在 DOM 中复选框之后,标签之前,导致标签转到下一行。我试过float:left,我试过inline-block,它仍然这样做。当绝对 div 被隐藏(未删除)时,它会恢复正常。并且当它再次验证时,div 会重新出现,但不会导致标签转到下一行。这个错误很老,跨多个版本。
【解决方案2】:

您可以利用 CSS 溢出或自动换行属性。

隐藏溢出:

overflow:hidden;

滚动溢出:

overflow:scroll;

也是滚动溢出,比较常用的方法:

overflow:auto;

或者,使用自动换行在指定区域拆分单词。

这会破坏单词:

word-wrap:break-word;

这正常换行:

word-wrap:normal;

【讨论】:

    【解决方案3】:

    我遇到了同样的问题,我找到的唯一解决方案是在有问题的单词周围添加 spanwhite-space: nowrap

    <!DOCTYPE HTML>
    <html>
    <head></head>
    <body>
      <div style='width:600px; background-color:red; position:relative; font-size:14px; font-family: monospace'>
        so much better to test it this way <span style='white-space: nowrap'>My_very_long_text<span style='position: absolute; width:20px; height:20px; background-color:green;'></span>_This_should_Not_be_on_next_line<span>
      </div>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2017-02-08
      • 2012-04-13
      • 1970-01-01
      • 2012-04-29
      • 2016-05-02
      • 1970-01-01
      • 2016-11-22
      • 2019-06-22
      • 1970-01-01
      相关资源
      最近更新 更多