๐ญ ์ ์ญ CSS ์ค์ผ: ์์ธก ๋ถ๊ฐ๋ฅํ ์คํ์ผ ์ถฉ๋๊ณผ ์ ์ง๋ณด์ ์ ๋ชฝ
Summary
์ ์ญ CSS๋ ์คํ์ผ ์ถฉ๋, ๋ฎ์ ์ฌ์ฌ์ฉ์ฑ, ์ ์ง๋ณด์ ์ด๋ ค์ ๋ฑ์ ์ผ๊ธฐํฉ๋๋ค. CSS Modules, Styled Components, Shadow DOM ๋ฑ์ ๊ธฐ์ ์ ์ฌ์ฉํ์ฌ CSS ์ค์ฝํ๋ฅผ ์ปดํฌ๋ํธ ๋จ์๋ก ์ ํํ๊ณ , CSS ๋ฐฉ๋ฒ๋ก ์ ์ ์ฉํ์ฌ ์คํ์ผ ๊ตฌ์กฐ๋ฅผ ๋ช ํํ๊ฒ ์ ์ํด์ผ ํฉ๋๋ค.
Why Wrong?
์ ์ญ CSS๋ ์คํ์ผ ๊ท์น์ด ์ ์ญ ๋ฒ์์ ์ ์ฉ๋๋ฏ๋ก, ์ปดํฌ๋ํธ ๊ฐ ์คํ์ผ ์ถฉ๋์ ์ ๋ฐํ๊ณ ์์ธก ๋ถ๊ฐ๋ฅํ ์คํ์ผ ๋ณํ๋ฅผ ์ด๋ํฉ๋๋ค. ํนํ ๋๊ท๋ชจ ํ๋ก์ ํธ๋ ์ฌ๋ฌ ํ์ด ํ์ ํ๋ ํ๊ฒฝ์์ CSS ์ ํ์ ๊ฐ์ ์ด๋ฆ ์ถฉ๋, ์คํ์ผ ์ฐ์ ์์ ๋ฌธ์ ๋ฑ์ผ๋ก ์ธํด ์์์น ๋ชปํ ์คํ์ผ ๊นจ์ง ํ์์ด ๋ฐ์ํ ์ ์์ต๋๋ค. ๋ํ, ์ ์ญ CSS๋ ์ปดํฌ๋ํธ์ ๋ ๋ฆฝ์ฑ์ ์ ํดํ๊ณ ์คํ์ผ ์ฌ์ฌ์ฉ์ฑ์ ๋จ์ด๋จ๋ ค ์ ์ง๋ณด์์ฑ์ ์ ํ์ํต๋๋ค. ๋ถํ์ํ ์คํ์ผ ์ฌ์ ์, CSS ํ์ผ ํฌ๊ธฐ ์ฆ๊ฐ, ๋๋ฒ๊น ์ด๋ ค์ ๋ฑ๋ ์ ์ญ CSS ์ฌ์ฉ์ ๋ฌธ์ ์ ์ผ๋ก ์ง์ ๋ ์ ์์ต๋๋ค.
How to Fix?
CSS Modules, Styled Components, Shadow DOM ๋ฑ์ ๊ธฐ์ ์ ์ฌ์ฉํ์ฌ CSS ์ค์ฝํ๋ฅผ ์ปดํฌ๋ํธ ๋จ์๋ก ์ ํํ๊ณ ์คํ์ผ ์ถฉ๋์ ๋ฐฉ์งํด์ผ ํฉ๋๋ค. CSS Modules๋ ๊ฐ CSS ํด๋์ค ์ด๋ฆ์ ๊ณ ์ ํ๊ฒ ์์ฑํ์ฌ ์ปดํฌ๋ํธ๋ณ๋ก ์คํ์ผ์ ๊ฒฉ๋ฆฌํฉ๋๋ค. Styled Components๋ ์ปดํฌ๋ํธ ๋ด๋ถ์ CSS๋ฅผ ์ง์ ์์ฑํ์ฌ ์คํ์ผ๊ณผ ์ปดํฌ๋ํธ ๊ฐ์ ๊ฒฐํฉ๋๋ฅผ ๋์ด๊ณ , props๋ฅผ ํตํด ๋์ ์ธ ์คํ์ผ์ ์ฝ๊ฒ ์ ์ฉํ ์ ์๋๋ก ํฉ๋๋ค. Shadow DOM์ ์น ์ปดํฌ๋ํธ์ ์คํ์ผ์ ์บก์ํํ์ฌ ์ธ๋ถ ์คํ์ผ์ ์ํฅ์ ๋ฐ์ง ์๋๋ก ํฉ๋๋ค. ๋ํ, BEM(Block, Element, Modifier)๊ณผ ๊ฐ์ CSS ๋ฐฉ๋ฒ๋ก ์ ์ ์ฉํ์ฌ CSS ํด๋์ค ๋ค์ด๋ฐ ๊ท์น์ ์ผ๊ด์ฑ ์๊ฒ ์ ์งํ๊ณ ์คํ์ผ ๊ตฌ์กฐ๋ฅผ ๋ช ํํ๊ฒ ์ ์ํ๋ ๊ฒ์ด ์ข์ต๋๋ค. CSS-in-JS ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ ๋๋ ๋ฐํ์ ์ค๋ฒํค๋๋ฅผ ๊ณ ๋ คํ์ฌ ์ ์คํ๊ฒ ์ ํํด์ผ ํฉ๋๋ค.
Before Code (Bad)
/* global.css */
.button {
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
/* ComponentA.css */
.button {
background-color: red; /* ์๋์น ์์ ์คํ์ผ ์ฌ์ ์ */
}
/* ComponentB.css */
.button {
font-size: 1.2em; /* ๋ ๋ค๋ฅธ ์๋์น ์์ ์คํ์ผ ์ฌ์ ์ */
}
```
```jsx
// ComponentA.jsx
import './ComponentA.css';
function ComponentA() {
return <button className="button">Button A</button>;
}
// ComponentB.jsx
import './ComponentB.css';
function ComponentB() {
return <button className="button">Button B</button>;
}
After Code (Good)
/* Button.module.css */
.button {
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
font-size: 1em;
}
.primary {
background-color: red;
}
```
```jsx
// Button.jsx
import styles from './Button.module.css';
function Button({ children, primary }) {
return (
<button className={`${styles.button} ${primary ? styles.primary : ''}`}>
{children}
</button>
);
}
// ComponentA.jsx
import Button from './Button';
function ComponentA() {
return <Button primary>Button A</Button>;
}
// ComponentB.jsx
import Button from './Button';
function ComponentB() {
return <Button>Button B</Button>;
}