新标题:我的观点是:当使用flexbox时,粘性元素的粘性特性不会被保留
P粉356128676
P粉356128676 2023-08-21 23:28:29
0
2
480
<p>我在这个问题上卡了一会儿,想分享一下这个 <code>position: sticky</code> + flexbox 的问题:</p> <p>我的粘性div在切换到flexbox容器视图后,突然在被包裹在flexbox父元素中时不再粘性。</p> <p><br /></p> <pre class="brush:css;toolbar:false;">.flexbox-wrapper { display: flex; height: 600px; } .regular { background-color: blue; } .sticky { position: -webkit-sticky; position: sticky; top: 0; background-color: red; }</pre> <pre class="brush:html;toolbar:false;"><div class="flexbox-wrapper"> <div class="regular"> 这是普通的盒子 </div> <div class="sticky"> 这是粘性的盒子 </div> </div></pre> <p><br /></p> <p>JSFiddle显示问题</p>
P粉356128676
P粉356128676

全部回复(2)
P粉239164234

在我的情况下,一个父容器应用了overflow-x: hidden;这个样式,这会破坏position: sticky的功能。你需要移除这个规则。

没有任何父元素应该应用上述的CSS规则。这个条件适用于所有父元素,直到(但不包括)'body'元素。

P粉311423594

由于弹性盒子元素默认为stretch,所有元素的高度都相同,无法进行滚动。

align-self: flex-start添加到粘性元素中,将高度设置为自动,从而实现了滚动并固定。

目前,这在所有主要浏览器中都得到了支持,但Safari仍需要使用-webkit-前缀,而除了Firefox之外的其他浏览器在使用position: sticky的表格时存在一些问题。

.flexbox-wrapper {
  display: flex;
  overflow: auto;
  height: 200px;          /* 不是必需的 -- 仅作为示例 */
}
.regular {
  background-color: blue; /* 不是必需的 -- 仅作为示例 */
  height: 600px;          /* 不是必需的 -- 仅作为示例 */
}
.sticky {
  position: -webkit-sticky; /* 适用于Safari */
  position: sticky;
  top: 0;
  align-self: flex-start; /* <-- 这是修复的地方 */
  background-color: red;  /* 不是必需的 -- 仅作为示例 */
}
<div class="flexbox-wrapper">
  <div class="regular">
    这是普通的盒子
  </div>
  <div class="sticky">
    这是粘性的盒子
  </div>
</div>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!