英文:
How to remove element's space occupied when use position:sticky?
问题
<div class="main">
<div class="sticky">
固定菜单
</div>
<div class="body">
正文
</div>
<div class="other">
其他正文
</div>
</div>
<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>
我想要移除红色框所占的空间,其中一个解决方案是将.sticky
置于position: absolute
中,但我不能更改HTML结构,有没有办法使它生效?谢谢!
<details>
<summary>英文:</summary>
The html struct
<div class="main">
<div class="sticky">
sticky menu
</div>
<div class="body">
body
</div>
<div class="other">
other body
</div>
</div>
The css style
<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>
[![sticky][1]][1]
I want to remove the space occupied by the red box, One of the solutions is make `.sticky` inside `position: absolute`, but I can't change html struct, any solution to make it work? Thanks
[1]: https://i.stack.imgur.com/rAVLI.png
</details>
# 答案1
**得分**: 1
一种想法是使用浮动(float),然后使用 shape-outside 使元素占用 0 空间。
```css
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; /* 这里 */
shape-outside: inset(50%); /* 还有这里 */
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>
英文:
One idea is to use float and then use shape-outside to make the element takes 0 space.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
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);
}
<!-- language: lang-html -->
<div class="main">
<div class="sticky">
sticky menu
</div>
<div class="body">
body
</div>
<div class="other">
other body
</div>
</div>
<!-- end snippet -->
答案2
得分: -1
Instead of position sticky, use position fixed and add padding to the body container.
英文:
Instead of position sticky, use position fixed and add padding to the body container
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论