我有一个粘性导航栏,当它粘贴(应用position: fixed
)时,宽度会改变,以将导航栏的右侧推离屏幕。
使用反应/钩子和样式化的组件。一个钩子正在应用sticky: true
的属性(请参见下面的代码)。
我尝试了非粘式和粘式两种设置width: 100%
或width: 100vw
的不同组合。
在视频中,您可以看到当导航栏变为“粘性”时发生的两件事。 border-radius-bottom-right消失,导航的内容被推到右边。不粘时,导航宽度为808px,粘时,导航宽度增长到840px。需要明确的是,我并不是说要删除边框半径样式,但是边框右侧现在不在屏幕上。
导航的代码:
const Wrapper = styled.div`
padding: 1rem;
display: flex;
justify-content: center;
font-size: 1.5rem;
background-color: white;
color: black;
/* width: auto; */
/* width: 100%; */
z-index: 1;
margin: 0;
box-shadow: 0px 2px 10px #273136;
height: 30px;
border-radius: 0 0 10px 10px;
${props => props.sticky && css`
position: fixed;
top: 0;
width: 100vw;
`}
`;
这是在另一个包装器组件内部呈现的,使用以下样式包装整个应用程序:
text-align: center;
font-size: 10px;
color: black;
display: flex;
flex-direction: column;
max-width: 100vw;
答案 0 :(得分:1)
您将widht:100vw
设置为比主体宽的固定元素,因为vw
并不在乎滚动条,因为滚动条很难使用,我建议您使用width:100%
此外,由于您将box-sizing
设置为content-box
,因此填充和边框不会被视为内容,因此它们会影响宽度,我们不要忘记默认的margin:8px
身体
为了容纳所有这些,我们可以使用calc()
您应该使用100vw
而不是100%
,因为100%为我们提供了父级的确切宽度,不包括滚动条的宽度。
解决方案
设置position:fixed
您还添加
left:8px; // to push it 8px from the left because of the default margins on the body
width:calc(100% - 48px);
为什么要48x
?
left padding (16p) + right padding(16px) + left body margin(8px) + right body margin(8px) = 48px
为什么左手边距?我们不是用left:8px
来处理它吗?
是的,我们通过推送它只是将它的另一端添加了。