CSS를 활용하여 스타일링하는 방법을 알아봅시다.


CSS를 활용한 스타일링은 3장 1. Split PhoneBook 파트에서 했던 방식과 동일합니다. 마땅히 특징이 존재하지는 않지만, 주의해야 할 점이 있습니다. 그 점은 바로 중복되는 클래스명이 있으면 안 된다는 점입니다. 여러 개의 컴포넌트들은 웹팩을 통해 합쳐지게 되는데 그 과정에서 스타일 파일도 같이 합쳐집니다. 그럼 만약 중복되는 클래스명이 있다면 둘 중 하나가 덮어쓰여지므로 원하는대로 CSS가 설정되지 않는다는 문제가 발생합니다.

이에 대한 해결책으로는 아예 다른 클래스명을 사용하는 방법도 있겠지만, CSS Selector 를 활용하는 방법도 있습니다. 아래의 예시를 보며 확인해봅시다.

.input_boxes {
  margin: 50px 0;
  display: flex;
  flex-direction: column;
}

.input_boxes .input_box {
  padding: 10px 0;
}

.input_boxes .input_box_name {
  margin-bottom: 3px;
}

.input_boxes .input_box_input {
  width: 100%;
  padding: 10px;
  font-size: 1rem;
  outline: none;
}

.input_boxes .input_box_button {
  margin-left: auto;
  width: 100px;
  padding: 10px;
  outline: none;
  border: 1px solid #495057;
  background: white;
  color: #495057;
  cursor: pointer;
  margin-top: 10px;
}

.input_boxes .input_box_button:hover {
  background: #495057;
  color: white;
}

위와 같이 제한을 걸어주는 것입니다. 특정 클래스명을 가진 요소 안의 것만 스타일이 적용되도록 말입니다.

하지만 이 과정은 css 파일을 더 복잡하게 만들 수 있습니다. 이에 대한 해결책으로 CSS Module이 있습니다. CSS Module은 css 클래스를 불러올 때 [파일 이름]_[클래스 이름]__[해쉬값]으로 고유한 클래스명을 부여하여 동일한 클래스명이 생기지 않게 만드는 기술입니다. 이를 적용하기 위해서는 css 파일을 [파일 이름].module.css 와 같이 저장해야 합니다. 아래의 예시를 봅시다.

.input_boxes {
  margin: 50px 0;
  display: flex;
  flex-direction: column;
}

.input_box {
  padding: 10px 0;
}

.input_box_name {
  margin-bottom: 3px;
}

.input_box_input {
  width: 100%;
  padding: 10px;
  font-size: 1rem;
  outline: none;
}

.input_box_button {
  margin-left: auto;
  width: 100px;
  padding: 10px;
  outline: none;
  border: 1px solid #495057;
  background: white;
  color: #495057;
  cursor: pointer;
  margin-top: 10px;
}

.input_box_button:hover {
  background: #495057;
  color: white;
}
import React from "react";
import styles from "./InputBox.module.css";

const InputBox = () => {
  return (
    <div className={styles.input_boxes}>
      <div className={styles.input_box}>
        <div className={styles.input_box_name}>이름</div>
        <input
          type="text"
          placeholder="이름"
          name="name"
          className={styles.input_box_input}
        />
      </div>
      <div className="input_box">
        <div className={styles.input_box_name}>전화번호</div>
        <input
          type="text"
          placeholder="전화번호"
          name="phone"
          className={styles.input_box_input}
        />
      </div>
      <button className={styles.input_box_button}>저장</button>
    </div>
  );
};

export default InputBox;

위와 같이 모듈화한 스타일 파일을 객체로 받아와서 "className={styles.[클래스명]}"과 같은 형식으로 클래스명을 지정해주고 있습니다. styles 객체는 아래와 같은 내용이 들어있습니다.