white-space 的三大应用-宽度自适应

Filed under: Css |
Posted on

语法:

white-space : normal | pre | nowrap

参数:

normal :  默认处理方式
pre :  用等宽字体显示预先格式化的文本。不合并字间的空白距离和进行两端对齐。参阅pre对象
nowrap :  强制在同一行内显示所有文本,直到文本结束或者遭遇br对象。参阅td,div等对象的nowrap属性(特性)

说明:

设置或检索对象内空格的处理方式。
对应的脚本特性为whiteSpace。请参阅我编写的其他书目。

上面的内容来自 苏沈小雨 的《css2.0中文手册》,很好用,推荐一下。

white-space有几处典型的应用:

1.宽度自适应. 先看代码

<div style="width:auto !important;min-width:40px;width:40px;height:40px;background:#cccccc;
color:#000000;">
fdafdasfdafdasfddsa<span style="color:#ff0000">这里有中文的时候ie6就会换行</span>fdasfdasfdasfdasfdasd
</div>

复制到你的body代码里看看,这里的代码都是在

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

运行测试的。

你会发现当有中文的时候,ie6就会断行,重新另起一行,无法达到自适应的目的,如果你加上 white-space:nowrap;就能解决了宽度自适应问题了。

2.ie下超出隐藏,并且出现省略号(只在ie下有效,firefox是截断处理)。

<div style="width:80px;height:40px;background:#cccccc;
color:#000000;overflow:hidden;text-overflow:ellipsis;">
fdafdasfdafdasfddsa<span style="color:#ff0000">这里如果没有white-space:nowrap,显示不出省略号的效果</span>
fdasfdasfdasfdasfdasd
</div>

ie下显示省略号的有四大要素,一个要有width:固定宽度,一个要有overflow:hidden,一个要有text-overflow:ellipsis ,还得有white-space:nowrap。white-space:nowrap 起到一个关键的作用,防止断行。

3.button,firefox下断行问题。

这个我还是把图传上来容易看一点

当文字跟按钮的宽度差不多宽的时候,ie下正常,但是firefox下会出现断行,

ie下

firefox下

在看下没有样式限制宽度的时候,按钮会根据文字的大小,左右有一定的padding值。

解决这个换行的你可以把宽度变大,把背景拉长,当然最简单的,就是加上 white-space:nowrap 。

Leave a Reply