프론트엔드/React
[React][CSS] 리액트 배경이미지 적용
순코딩
2023. 12. 31. 16:25
1. public 폴더 아래 background.jpg 이미지를 넣는다
2. 아래 코드 참고하여 배경 이미지를 적용할 DOM에 background-image 속성을 적용한다
const Background = styled.div`
height: 100%;
background-image: url("./background.jpg");
background-repeat: no-repeat; /* 배경 이미지 반복 설정 */
background-size: cover; /* 배경 이미지 크기 조절 (cover, contain 등) */
background-position: center; /* 배경 이미지 위치 조절 */
`;
+ 필자는 아래 참고자료를 참고해 경로를 background-image: url("/background.jpg"); 로 설정해봤으나 알 수 없는 이유로 이미지가 뜨지 않고 콘솔에도 오류가 뜨지 않았다.
+ 해결을 위해 이미지 경로를 background-image: url("./background.jpg"); 으로 수정하였더니 버그가 고쳐졌다.
원인은 현재까지도 모르겠다.(리액트는 결국 public 폴더 내에서 구동되기 때문에 ./ 경로를 사용해야 경로가 더 잘 추적되는 지도 모르겠다.)
<참고자료>
React Background Image Tutorial – How to Set backgroundImage with Inline CSS Style
There are four ways to set a backgroundImage style property using React's inline CSS. This tutorial will show you all four methods, with code samples for each. Here's an Interactive Scrim of Setting a Background Image with React How to Set a Background Ima
www.freecodecamp.org