Home > Blockchain >  Position a nested div relative to viewport
Position a nested div relative to viewport

Time:12-14

I'm building an element( Component in react), that can enclose a child component/element. There are some styles defined on the element. The element should have styles such that, it'd allow the child element to be positioned anywhere on the screen (i.e, relative to the viewport). There are 2 catches, however,

  1. I can't set the custom element's height and width to be 100% with position: absolute, because there's an element behind this element that needs to be visible and clickable (My first approach was to set opacity:0 on the custom element so that the element behind could be visible, but this would not make it clickable).
  2. The child element is conditionally mounted/unmounted, so during this process a scrollbar is visible and it goes away after the mounting/unmounting completes, making it to a not-so-good UI.

Let's call the custom element ABC. The HTML structure would look something like this:

<ABC props>
  <div><p>Child element</p></div> //This could be anything for the matter of fact.
</ABC>

CSS of ABC component:

    position: absolute;
    z-index: 25;
    top:0;
    margin: 0 auto;
    border: 5px solid blue;
    transform: translateY(15px);
    transition: opacity 1s ease,transform 1s ease; 

In the above case, I'd want to be able to apply styles to the child div element so that it can be positioned anywhere relative to the viewport, and occupy any size as specified. I did try using position: fixed with other combinations, but none seem to solve the issue.

Any input is appreciated. Thanks.

CodePudding user response:

You can either:

  • have a container 100% height/width of viewport and disable mouse interactions on it with pointer-events and touch-events (and re-enable them on the child element)
  • use position:fixed and vh/vw units on top/left properties for position

References:

  • Related