overflow 属性
overflow 属性是你控制一个元素溢出的方式,它告诉浏览器你想怎样处理溢出。overflow 的默认值为 visible,这就是我们的内容溢出的时候,我们在默认情况下看到它们的原因。
如果你想在内容溢出的时候把它裁剪掉,你可以在你的盒子上设置 overflow: hidden。这就会像它表面上所显示的那样作用——隐藏掉溢出。这可能会很自然地让东西消失掉,所以你只应该在判断隐藏内容不会引起问题的时候这样做。
html
This box has a height and a width. This means that if there is too much
content to be displayed within the assigned height, there will be an overflow
situation. If overflow is set to hidden then any overflow will not be visible.
This content is outside of the box.
css.box {
border: 1px solid #333333;
width: 250px;
height: 100px;
overflow: hidden;
}
也许你还会想在有内容溢出的时候加个滚动条?如果你用了 overflow: scroll,那么你的浏览器总会显示滚动条,即使没有足够多引起溢出的内容。你可能会需要这样的样式,它避免了滚动条在内容变化的时候出现和消失。
如果你移除了下面的盒子里的一些内容,你可以看一下,滚动条是否还会在没有能滚动的东西的时候保留。
html
This box has a height and a width. This means that if there is too much
content to be displayed within the assigned height, there will be an overflow
situation. If overflow is set to hidden then any overflow will not be visible.
This content is outside of the box.
css.box {
border: 1px solid #333333;
width: 250px;
height: 100px;
overflow: scroll;
}
在以上的例子里面,我们仅仅需要在 y 轴方向上滚动,但是我们在两个方向上都有了滚动条。你可以使用 overflow-y 属性,设置 overflow-y: scroll 来仅在 y 轴方向滚动。
html
This box has a height and a width. This means that if there is too much
content to be displayed within the assigned height, there will be an overflow
situation. If overflow is set to hidden then any overflow will not be visible.
This content is outside of the box.
css.box {
border: 1px solid #333333;
width: 250px;
height: 100px;
overflow-y: scroll;
}
你也可以用 overflow-x,以在 x 轴方向上滚动,尽管这不是处理长英文词的好办法!如果你真的需要在小盒子里面和长英文词打交道,那么你可能要了解一下 word-break 或者 overflow-wrap 属性。除此以外,一些在 CSS 里面调整大小这节课里面讨论过的方式可能会帮助你创建可以和有变化容量的内容相协调的盒子。
html
css.word {
border: 5px solid #333333;
width: 100px;
font-size: 250%;
overflow-x: scroll;
}
和 scroll 一样,在无论是否有多到需要 用滚动条的内容的时候,页面上都会显示一个滚动条。
备注:
你可以用 overflow 属性指定 x 轴和 y 轴方向的滚动,同时使用两个值进行传递。如果指定了两个关键字,第一个对 overflow-x 生效而第二个对 overflow-y 生效。否则,overflow-x 和 overflow-y 将会被设置成同样的值。例如,overflow: scroll hidden 会把 overflow-x 设置成 scroll,而 overflow-y 则为 hidden。
如果你只是想让滚动条在有比盒子所能装下更多的内容的时候才显示,那么使用 overflow: auto。此时由浏览器决定是否显示滚动条。桌面浏览器一般仅仅会在有足以引起溢出的内容的时候这么做。
在下面的例子里面,移除一些内容,直到能够装在盒子里面,你还会看到滚动条消失了。
html
This box has a height and a width. This means that if there is too much
content to be displayed within the assigned height, there will be an overflow
situation. If overflow is set to hidden then any overflow will not be visible.
This content is outside of the box.
css.box {
border: 1px solid #333333;
width: 250px;
height: 100px;
overflow: auto;
}