Reputation: 9888
How can I setup a container so when the window size is too small shows a scroll in order to see all the elements that doesn't fit in one go, but at the same time, if a child shows a floating elements it is allowed to exit the bounds of the container.
I am currently using a Material UI Card, which has some elements:
As you can see in the image, it works while using overflow: auto
for the CardContent.
Unfortunately, the floating element for the Combo1 component is not allowed to be shown outside:
And if I remove the overflow and/or set it to overflow: visible
, the floating element shows fine but the contents doesn't scroll anymore:
Is there any way to allow only the floating elements to be shown outside a parent with hidden overflow?
Upvotes: 1
Views: 1247
Reputation: 35705
Your core issue is that A) if you have content inside an element, B) that content exceeds the element's width, and C) that element has an overflow
style that hides content that content will be hidden. This is just how CSS works.
Similarly, if you don't hide your overflow, there's no way to have the browser add scroll bars to that content. So if you want scrolled content you have to have an appropriate overflow
style (auto
scroll-y
, scroll
) to get the scrolling you want.
The solution, which will feel unnatural in a React app (where you're used to keeping all your UI within your component's HTML element) is to keep any UI bits that need to be shown outside the overflow, outside of the element with the overflow style.
They can still be in the same component, they just have to be outside the main element. Then, you can use some onComponentDidMount (useEffect
) code to position that UI to appear next to the scrolling UI. In other words, you can't change overflow
or your DOM structure, but you can use CSS to make your UI look the way you desire with a different structure.
Something like:
const YourComponent => {
useEffect(positionUiBitsNextToMainUIUsingRefsOrSomething);
return <>
<UIBits/>
<div style={{overflow: 'auto'}}>
<MainUI/>
</div>
</>;
}
As for doing the positioning part, you'll need to use refs (useRef
) to access the DOM elements of your UI, so that you can position them. Prior to React I would use jQuery UI's position
function to do this sort of thing, but haven't needed to do this in React (or anywhere else) in a long time, so I don't have a better recommendation.
Whether you use a library or not though, essentially you'll want to use position: absolute
styling (and some calculations on your main UI's position) to move the UI bits to where you want them.
Upvotes: 1