🔥 문제
현재 모달 위치는 정 중앙에 위치하고 있다.
그러나 나는, 모달 위치를
MainContainer
안에 위치시키고 싶다.그렇다면 모달 위치를 어떻게 하면 MainPage에 맞출 수 있을까?

⭐ 해결 방법
fixed
의 너무나 깐깐한 규정
일단 원인을 명확히 하자.
fixed
는 항상 화면을 기준으로 위치를 고정시킨다.따라서
fixed
로 한다면, MainContainer
가 있는 위치에 대한 top
, left
, bottom
, right
의 값을 명확히 전달시켜줘야 한다.따라서 이는 좋은 방법이 아닌 듯했다.
따라서 나는 먼저,
postion:absolute
로 고정시켜줬다.아니, 그러면 결국 스크롤 하면 어쩌려고?!
노놉, 괜찮다.
왜냐하면, 나는
BackgroundDim
으로 한 번 fixed
로 전체 화면을 감쌌기 때문이다.다음 코드를 살펴 보자.
const BackgroundDim = styled.div` position: fixed; top: 0; left: 0; z-index: 1000; width: 100vw; height: 100vh; background-color: rgb(0 0 0 / 50%); `; const ModalContainer = styled.div` position: absolute; top: 50%; left: 50%; box-sizing: border-box; display: flex; flex-direction: column; align-items: center; padding: ${({ padding }) => typeof padding === 'string' ? padding : `${padding}px`}; background-color: white; border-radius: 20px; box-shadow: 0 3px 6px rgb(0 0 0 / 20%); transform: translate(-50%, -50%); ${({ width, height }: Partial<ModalProps>) => css` width: ${typeof width === 'string' ? width : `${width}px`}; height: ${typeof height === 'string' ? height : `${height}px`}; `} `;
즉, 나는
BackGroundDim
이 fixed하므로, 하위 컴포넌트만 absolute
로 하면 스크롤로 인한 당황스러움을 극복할 수 있다.새로운 꼼수 발견 - MainContainer
로 ModalContainer
을 감싸면?
만약
MainContainer
의 값으로 ModalContainer
을 감싸면, 어떨까?MainContainer
가 position이 relative하다면 모달의 기준이 부모 컴포넌트에 종속될 것이고, 결과적으로 MainContainer 안에 집어 넣어줄 수 있을 것이라 생각했다.따라서 다음과 같이
ModalContainer
로 감싸줬다.@components/atoms/MainContainer
position: relative;
@components/atoms/Modal.tsx
return createPortal( <BackgroundDim style={{ display: visible ? 'block' : 'none' }}> <MainContainer paddingWidth={24}> <ModalContainer width={width} height={height} padding={padding} ref={ref} {...props} > {children} </ModalContainer> </MainContainer> </BackgroundDim>, el ); };
결과
해당 모달 컴포넌트가 MainContainer 위치에 잘 들어가 있다 🙂
