浮动元素永远不会脱离div

时间:2013-09-30 16:41:27

标签: html css

关注我的代码:

HTML:

<div>aaaaaaaaaaaaaaa
    <span>test</span>
</div>

CSS:

div{
    width: 60px;
    border-bottom: 1px solid red;
    word-break:break-all;
}
span{
    float: right
}

我会得到这个结果:http://oi41.tinypic.com/2py25w1.jpg
我希望正确浮动的文本不应该离开div,所以它必须在需要时转到div内的新行,就像我发布的代码一样。 在这种情况下,例如,没有必要在新行中放开文本,因为文本适合文本的右侧:http://jsfiddle.net/3kRan/2/

2 个答案:

答案 0 :(得分:0)

将div上的溢出设置为隐藏,如下所示:

div{
    width: 60px;
    border-bottom: 1px solid red;
    word-break:break-all;
    overflow: hidden;

}

当span尝试浮动时,您的内容会溢出。这将允许您的跨度保持在其父容器中。

答案 1 :(得分:0)

此答案取决于您将文本包装在元素中的能力,例如p。最终结果将是:

<div><p>aaaaaaaaaa</p>
  <span>test</span>
</div>
div{
  width: 60px;
  border-bottom: 1px solid red;
  word-break:break-all;
  height: 100%; 
  overflow: auto; /* fix to clear the parent */
}
p {
  padding:0;
  margin:0;
}
span{
  float: right
}

更新了小提琴:http://jsfiddle.net/3kRan/5/