简体   繁体   English

我如何在 React.js 中使用 overflow:hidden 和 position:sticky

[英]How do I use overflow:hidden as well as position:sticky in React.js

I have been trying to use overflow:hidden because the navbar I created seem to be creating a White space on the right of my webpage.我一直在尝试使用 overflow:hidden ,因为我创建的导航栏似乎在我的网页右侧创建了一个空白区域。 I have used Header component to create the navbar.我使用 Header 组件来创建导航栏。 I also wanted the navbar to be position: sticky.我还希望导航栏处于位置:粘性。 I found out I can use either but not both.我发现我可以使用其中一个,但不能同时使用。 Is there any way around this?有没有办法解决?

Unfortunately this has nothing to do with React.不幸的是,这与 React 无关。 It's just a css problem.这只是一个css问题。 You cannot use position: sticky inside a overflow: hidden .您不能在overflow: hidden内使用position: sticky
(see: https://github.com/w3c/csswg-drafts/issues/865 ) (见: https : //github.com/w3c/csswg-drafts/issues/865

If you want that effect, you'll need to use a sticky js library (such as http://stickyjs.com/ ), or calculate the position on your own (with position: fixed or position: absolute ).如果您想要这种效果,则需要使用粘性 js 库(例如http://stickyjs.com/ ),或者自己计算位置(使用position: fixedposition: absolute )。

The good news is that you probably don't need that overflow: hidden .好消息是你可能不需要那个overflow: hidden If there's a space on the right, it's just an element overflowing, so you should address only that element and not the whole container.如果右边有一个空格,它只是一个元素溢出,所以你应该只处理那个元素而不是整个容器。 (It's usualy margin,elements with fixed width or elements with position absolute outside the viewport) (通常是边距、固定宽度的元素或在视口外具有绝对位置的元素)

Try this first.先试试这个。 Becaue you dont know the gap between the sticky element and viewport boundary, you may insert his in your css rule:因为你不知道粘性元素和视口边界之间的差距,你可以在你的 css 规则中插入他的:

element {
overflow: hidden;
position: sticky;
top: 0; // this will get rid of gap
}

You can alternatively use following.您也可以使用以下方法。 You might have space because you have given dynamic width and maybe you have padding, margin etc defined as well.您可能有空间,因为您已经给出了动态宽度,并且您可能还定义了padding, margin等。 If you had posted code snippet it would have helped better but I had done my styling with followings.如果您发布了代码片段,它会有所帮助,但我已经使用以下内容完成了我的样式。 flex-root being used as display had helped as well.用作显示的flex-root也有帮助。 Only try if above way doesnt work.只有在上述方法不起作用时才尝试。

  //  Try CSS attributes:
element {
word-break: break-word;
}

// if you have padding which is creating white space:
element {
width: auto;
padding: 0;
word-break: break-word;
}
// Try this as well
element {
display: flex-root;
}

// display flex guidelines:
// https://developer.mozilla.org/en-US/docs/Web/CSS/display
// The element generates a block element box that establishes a new block formatting 


----------


context, defining where the formatting root lies

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM