我正在尝试构建一个与右侧对齐的粘性工具栏。但我无法让它与那一侧对齐:
如果我使用float: right;下面的元素,就会被拉起,如果我使用父容器,它会跨越整个屏幕宽度并使用,justify-content: end;并且使用z-index: 10;左右,该父元素的屏幕会被阻止。
那么如何才能最优雅地将元素对齐到右侧呢?
.container {
background-color: cyan;
height: 1000px;
}
.sticky-element {
position: sticky;
top: 20px;
}
.other-stuff {
padding: 20px;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<div class="sticky-element">
<button>Button 1</button>
<button>Button 2</button>
</div>
<div class="other-stuff">
Some other stuff that is drawn up if float: right is applied on sticky-element.
(But shouldn't)
</div>
</div>Run Code Online (Sandbox Code Playgroud)
您可以设置 awidth:max-content和 a margin-left:autoon .sticky-element,如下所示:
.container {
background-color: cyan;
height: 1000px;
}
.sticky-element {
position: sticky;
top: 20px;
width:max-content;
margin-left:auto;
}
.other-stuff {
padding: 20px;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<div class="sticky-element">
<button>Button 1</button>
<button>Button 2</button>
</div>
<div class="other-stuff">
Some other stuff that is drawn up if float: right is applied on sticky-element.
(But shouldn't)
</div>
</div>Run Code Online (Sandbox Code Playgroud)