css 如何移除使用position:sticky时元素所占用的空间?

qv7cva1a  于 2023-07-01  发布在  其他
关注(0)|答案(4)|浏览(197)

HTML结构

<div class="main">
  <div class="sticky">
    sticky menu
  </div>
  <div class="body">
    body
  </div>
  <div class="other">
    other body
  </div>
</div>

CSS风格

<style>
 html body {
     margin: 0;
     padding:0 ;
     height: 100%;
     width: 100%;
 }
 .main {
     width:100%;
     max-width: 300px;
     height: 480px;
     margin: 0 auto;
     background-color: yellow;
     position: relative;
     margin-top: 50px;
 }
 .body {
     height: 720px;
 }
 .sticky {
     position: sticky;
     z-index:10;
     top: 0;
     background-color: blue;
     display: inline-block;
     transform: translate(-100%,0);
 }
</style>

我想删除红色框所占的空间,其中一个解决方案是在position: absolute内部创建.sticky,但我不能更改html结构,有什么解决方案可以让它工作吗?谢谢

mgdq6dx1

mgdq6dx11#

一个想法是使用float,然后使用shape-outside使元素占用0空间。

body {
  margin: 0;
}

.main {
  max-width: 300px;
  height: 480px;
  margin: 0 auto;
  background-color: yellow;
  position: relative;
  margin-top: 50px;
}

.body {
  height: 720px;
}

.sticky {
  position: sticky;
  z-index: 10;
  top: 0;
  background-color: blue;
  float: left; /* here */
  shape-outside: inset(50%); /* and here */
  transform: translate(-100%, 0);
}
<div class="main">
  <div class="sticky">
    sticky menu
  </div>
  <div class="body">
    body
  </div>
  <div class="other">
    other body
  </div>
</div>
wnrlj8wa

wnrlj8wa2#

代替位置粘性,使用位置固定,并为正文容器添加填充

628mspwn

628mspwn3#

您可以使用position: fixed;代替position: sticky;

gr8qqesn

gr8qqesn4#

如果主块是柔性的,那么其中的所有块都将被压到最顶部。

html body {
    margin: 0;
    padding:0 ;
    height: 100%;
    width: 100%;
    }
    .main {
    display:flex; /* main pushes up */
    width:100%;
    max-width: 300px;
    height: 480px;
    margin: 0 auto;
    background-color: yellow;
    position: relative;
    margin-top: 50px;
    }
    .body {
    height: 720px;
    }
.sticky {
    position: sticky;
    z-index:10;
    top: 0;
    height:100px; /* height container */
    background-color: blue;
    display: inline-block;
    transform: translate(-100%,0);
}

相关问题