简单了解 overflow: clip 属性

5,517 阅读3分钟

大家都知道overflow之前有几个属性:visiblehiddenscrollauto。这几个属性就不详解了。而最近Chrome 刚发布的90版本中,又支持了一个新的值clip,以及配合它使用的overflow-clip-margin属性。 来看看overflow: clip的意思:

Like for hidden, the content is clipped to the element's padding box. The difference between clip and hidden is that the clip keyword also forbids all scrolling, including programmatic scrolling. The box is not a scroll container, and does not start a new formatting context. If you wish to start a new formatting context, you can use display: flow-root to do so. overflow-clip-margin的意思 : The overflow-clip-margin CSS property determines how far outside its bounds an element with overflow: clip may be painted before being clipped.

好复杂。先来看个简单的例子吧。

overflow.png

.box{
  margin: 10px;
  width: 200px;
  height: 100px;
  border: solid 1px;
}

.hidden{
  margin: 10px;
  width: 200px;
  height: 100px;
  overflow: hidden;
  border: solid 1px;
}

.clip{
  width: 200px;
  height: 100px;
  overflow: clip;
}

.margin{
  overflow-clip-margin: 30px
}

请戳此预览>>>>

乍一看,overflow: clip在单独使用的时候,和overflow: hidden没啥区别,只是在使用overflow: clip之后,我们可以设置一个溢出内容裁切的值,来控制溢出显示的区域。

但是我们看官方解释有一句:The box is not a scroll container, and does not start a new formatting context. If you wish to start a new formatting context, you can use display: flow-root to do so.,这是啥意思呢,再来看一个例子:

这是从MDN官网上扒来的一个关于BFC的代码例子。在下面的示例中,我们在应用了边框的 div 中有一个浮动元素。该 div 的内容与浮动元素一起浮动。由于float的内容比它旁边的内容高,所以现在DIV的边框贯穿了float。

.box {
    width: 400px;
    background-color: rgb(224, 206, 247);
    border: 5px solid rebeccapurple;
}

.float {
    float: left;
    width: 200px;
    height: 150px;
    background-color: white;
    border:1px solid black;
    padding: 10px;
}   

显示的效果如下:

QQ截图20210419175835.png

如果我们给父元素box加上overflow: hidden,会自动创建包含浮动的新 BFC。现在,我们的DIV在布局中变成了一个迷你布局。任何子元素都将包含在其中,如图:

.box {
    width: 400px;
    background-color: rgb(224, 206, 247);
    border: 5px solid rebeccapurple;
    overflow: hidden;
}

QQ截图20210419180127.png

如果将overflow: hidden 替换成为 overflow: clip,那么将显示如下图:

.box {
    width: 400px;
    background-color: rgb(224, 206, 247);
    border: 5px solid rebeccapurple;
    overflow: clip;
}

QQ截图20210419180424.png

由于没有创建格式化上下文,所以直接把多余的部分裁切掉了。 如果想显示完成,再加一句display: flow-root即可。

.box {
    width: 400px;
    background-color: rgb(224, 206, 247);
    border: 5px solid rebeccapurple;
    overflow: clip;
    display: flow-root;
}

戳此试一试>>>>

Chrome官网还给出了一个说明:

Using overflow: clip makes it possible for you to prevent any type of scrolling for the box, including programmatic scrolling. That means the box is not considered a scroll container; it does not start a new formatting context, which gives it better performance than overflow: hidden. And if you need it, you can apply clipping to a single axis via overflow-x and overflow-y.`

overflow: clip使用的时候不会创建格式化上下文,这样在性能方面,相对overflow:hidden是要好一些的。

然而现在90版本刚发布,要等到这个属性能广泛使用,还有很远的距离……

参考:

developer.chrome.com/blog/new-in…

developer.mozilla.org/en-US/docs/…