[CSS] 리액트 스타일링 방식 1
[CSS] 리액트 스타일링 방식 1
전통적인 방식의 스타일링
인라인 스타일
- HTML 태그의
style속성을 사용해서 CSS 스타일을 지정하는 방식style속성에는 객체 형식의 값이 할당.font-size와 같은 케밥 케이스는 카멜 케이스로 작성.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
export default function Example1() { return ( <> <h1 style=>내 웹사이트</h1> </> ); } export default function Example2() { const style = { color: "red", textDecoration: "underline" }; return ( <> <h1 style={style}>내 웹사이트</h1> </> ); }
글로벌(외부) 스타일
- 별도의 CSS 파일에 CSS 코드를 작성하고, 컴포넌트 파일과 연결해서 사용하는 방법
css 파일 생성 후, 코드 작성
1 2 3 4 5
.title { color: blue; text-decoration: underline; } <!-- App.css -->
컴포넌트 파일
1 2 3 4 5 6 7 8 9
import "./App.css"; export default function App() { return ( <> <h1 className="title">Test</h1> </> ); }
컴포넌트 트리에 연결된 다른 컴포넌트 파일
→ 한번 더 import를 하지 않아도, css가 전역으로 적용되어 사용 가능.1 2 3 4 5 6 7
export default function 다른컴포넌트() { return ( <> <h1 className="title">Test</h1> </> ); }
좀 더 용이하게 관리하려면,
css폴더를 하나 생성하여 css 파일을 관리하여 불러오자.
CSS 모듈
- 글로벌 스타일 방식은 컴포넌트 트리 내의 모든 컴포넌트가 스타일이 적용된다는 특징이 있다.
- 이 방식은 모듈 방식을 사용해서 특정 컴포넌트에만 종속되는 CSS 코드를 작성할 수 있다.
- 외부 스타일 방법과 비슷하지만, 파일명이
*.module.css라는 특징이 있다. css 파일 생성 후, 코드 작성 → 이 때, 파일명은
*.module.css로 끝나야 한다.1 2 3 4
.underline { text-decoration: underline; } <!-- Footer.module.css -->
특정 컴포넌트에 특정 css 적용.
1 2 3 4 5 6 7 8 9 10 11
import **styles** from "./Footer.module.css"; export default function Example() { return ( <> <footer> <p className={styles.underline}>© 2024 내 웹사이트. 모든 권리 보유.</p> </footer> </> ); }
다음과 같이 모듈 방식을 사용하면, 클래스명이 암호화되어 나타나는 것을 확인 가능.
특정 컴포넌트에 여러 css 적용.
`(백틱)을 사용하여, 공백으로 구분하여 나타낸다.1 2 3 4 5 6 7 8 9 10 11 12 13
import styles from "./Footer.module.css"; export default function Example() { return ( <> <footer> <p className={`${styles.underline} ${styles["red-color"]}`}> © 2024 내 웹사이트. 모든 권리 보유. </p> </footer> </> ); }
classnames 패키지 사용
먼저, classnames 패키지 설치
1
npm i classnames
이전에 작성한 CSS 모듈 예제를 가져와 다음과 같이, 수정한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import styles from "./Footer.module.css"; import classNames from "classnames/bind"; // classnames 패키지 불러오기 export default function Example() { const cx = classNames.bind(styles); // 특정 css 바인딩 return ( <> <footer> <p className={cx("red-color", "underline")}> © 2024 내 웹사이트. 모든 권리 보유. </p> </footer> </> ); }
"classnames/bind": classnames 패키지의 bind 불러오기.classNames.bind(CSS명): 특정 css 바인딩.패키지바인딩명(속성값나열): 콤마(,)로 구분하여 여러개 적용 가능.
자세한 사용법은 npm 패키지에 명시되어 있음.
This post is licensed under CC BY 4.0 by the author.