HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🌟
Programmers 최종 플젝 6조
/
[프론트] TWL
[프론트] TWL
/
모달 위치를 MainContainer에 맞추는 방법
모달 위치를 MainContainer에 맞추는 방법
모달 위치를 MainContainer에 맞추는 방법

모달 위치를 MainContainer에 맞추는 방법

생성일
Dec 17, 2021 03:08 PM
태그
React
CSS
작성자
해결 완료
해결 완료

🔥 문제

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

⭐ 해결 방법

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 위치에 잘 들어가 있다 🙂
notion image

👏🏻 참고자료

https://velog.io/@imjkim49/CSS-Positionrelative-absolute-fixed-위치-결정