为什么需要深入学习CSS溢出机制? 在实际开发的过程中,内容溢出是经常见到的。如果不深入了解这个机制,你经常会碰到这样的问题:为什么这个元素没有受到祖先元素的overflow:hidden的影响?这里出现的滚动条是哪个元素的?如果消除这个滚动条?如何在指定的元素上增加滚动功能? 在这篇文章,我们将会从CSS标准出发,讨论CSS溢出机制的细节。 溢出 当一个盒子(blockcontainerbox)的内容(子元素、孙子元素等后裔)超过盒子本身的大小的时候,就会出现溢出。这个时候CSS属性overflow决定如何处理溢出。这个css属性大家都知道,在这里不讨论了,在这里指出需要注意的几点: overflow会影响所在元素的所有内容的裁剪、滚动,但是有一种情况例外:"Itaffectstheclippingofalloftheelement'scontentexceptanydescendantelements(andtheirrespectivecontentanddescendants)whosecontainingblockistheviewportoranancestoroftheelement."也就是说,overflow的所在元素必须是内容元素的直接或间接containingblock,这时overflow属性才会影响这个内容元素。比如<B><C><C/><B/>,一般来说,B的overflow会影响C,但是如果C是相对于viewport或者A定位的(比如使用了position:absolute),那么C的显示就不受B的裁剪、滚动的影响。 当需要滚动条的时候,滚动条会放在border与padding之间。父元素产生滚动条以后,它产生的containingblock的尺寸会减少,以便给滚动条腾出空间。 在<html>和<body>上的overflow属性存在冒泡现象:"UAsmustapplythe'overflow'propertysetontherootelementtotheviewport.WhentherootelementisanHTML"HTML"elementoranXHTML"html"element,andthatelementhasanHTML"BODY"elementoranXHTML"body"elementasachild,useragentsmustinsteadapplythe'overflow'propertyfromthefirstsuchchildelementtotheviewport,ifthevalueontherootelementis'visible'.The'visible'valuewhenusedfortheviewportmustbeinterpretedas'auto'.Theelementfromwhichthevalueispropagatedmusthaveausedvaluefor'overflow'of'visible'." 可以推断出: 一般来说只有元素才能拥有滚动条(更准确地说,只有产生blockcontainerbox的元素才能拥有滚动条)。但visualviewport是个例外。它虽然不是一个元素,但是也可以拥有滚动条。如果在<html>和<body>上都没有设置overflow属性而使用默认值visible(大部分场景都是这样),那么,visualviewport的overflow就是auto:当网页中有内容超出visualviewport时,visualviewport上会出现滚动条。 <html>的最终overflow永远都是visible。也就是说,<html>元素永远不可能拥有滚动条。 如果你想要为<body>设置非visible的overflow,需要先为<html>设置一个非visible的值来冒泡,从而<body>的overflow不会被冒泡。 小练习 小练习:利用以上原理,使visualviewport和<body>都拥有横、竖滚动条,总共4个滚动条。不能使用overflow:scroll(这样就太简单了)。 步骤: 使visualviewport和<body>的最终overflow值都为auto,从而可以出现滚动条。 触发visualviewport和<body>的溢出。通过【为内容设置一个更大的尺寸】来做到。 代码+注释: <!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <metaname="viewport"content="width=device-width,initial-scale=1,user-scalable=no"> <title>test</title> <style> *{ padding:0; margin:0; box-sizing:border-box; } html{ /*使html的尺寸始终与visualviewport相同(即使你缩放、调整浏览器窗口的大小),从而body可以设置一个比visualviewport还大的尺寸(110%)。 对于默认为block的元素可以省略width:100%;*/ width:100%; height:100%; /*非visible的值冒泡到visualviewport上,使visualviewport可以出现滚动条*/ overflow:auto; border:15pxsolidred; } body{ /*使得body可以出现滚动条*/ overflow:auto; /*body溢出html,从而溢出initialcontainningblock,从而溢出visualviewport,使得visualviewport出现滚动条。 当然,你也可以通过很多其他的方式来触发visualviewport的溢出,比如增大html元素,或者在body中弄一个position:absolute的p*/ width:110%; height:110%; border:15pxsolidgreen; } main{ /*main溢出body,使得body出现滚动条*/ width:110%; height:110%; border:15pxsolidblue; } </style> </head> <body> <main> </main> </body> </html>
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有