퍼블리싱/기타

[반응형] css 단위 px/em/rem

리리히히 2024. 3. 11. 20:29
반응형

 

🔎 절대단위

  • px(픽셀), pt(포인트)

 

🔎 상대단위

  • 고정적이지 않고 기준에 따라 유동적으로 바뀜
  • em, rem, % 등

 


🔎 em과 rem

 

📌 em

  • 현재의 font-size를 정의
  • 부모요소인 html에 100% 기준을 두고 하위 요소 들의 폰트사이즈가 결정
  • em은 요소의 글꼴 크기 1em을 갖는다.

 

<style>
    .content {font-size: 16px;}
    .content h2 {font-size: 2em;}
    .content p {font-size: 1.5em}
    .content p span {font-size: 0.5em}
</style>
<body>
    <div class="content">
    	<h2>h2타이틀 영역</h2>
    	<p>p텍스트
          <span>p태그 내부의 span 텍스트</span>
        </p>
    </div>
</body>


✅ 위와 같은 경우라면?

  • h2태그 : 16px * 2 = 32px
  • p태그 : 16px * 1.5 = 24px
  • span의 경우에는 content 영역 ➡️ p태그 영역 ➡️ span 태그이므로 16*1.5*0.5 = 12px

 


 

 

📌 rem

  • rem의 r은 root를 뜻함
  • rem의 경우 html 최상위 요소의 font-size를 1rem으로 설정
<style>
    .content {font-size: 16px;}
    .content h2 {font-size: 2rem;}
    .content p {font-size: 1.5rem}
    .content p span {0.5rem}
</style>
<body>
    <div class="content">
    	<h2>h2타이틀 영역</h2>
        <p>p텍스트
          <span>p태그 내부의 span 텍스트</span>
        </p>
    </div>
</body>

 

✅ 위와 같은 경우라면?

  • <content>
      16px * 2 = 32px
  • <p>
      16px * 1.5 = 24px
  • <span>
      16px*0.5=8px

 




📌 상황에 따라서 em을 사용하는 경우와 rem을 사용하는 경우가 나뉘지만 rem을 우선적으로 사용하는 것을 추천.
📌 em을 사용하는 경우 변수 px들이 많아지면서 유지보수에 있어 어려움을 느낄 수 있다.



 

✅ iOS에서 rem이 적용되지 않을 때 해당 태그를 html 또는  body에 추가해 준다.

-webkit-text-size-adjust: none;



✅ 디바이스 사이즈에 따라(반응형) 폰트 사이즈게 변경하게 하려면 rem과 mediaquery를 함께 사용해야 한다.

width: 640px 일때, 125%의 1rem = 20px
width: 320px 일때, 62.5%의 1rem = 10px

//반응형 미디어쿼리 예시

html {
    font-size: 62.5%;
    -webkit-text-size-adjust:none;
}

@media screen and (min-width: 280px){
    html {
        font-size: 50%
    }
}

@media screen and (min-width: 320px){
    html {
        font-size: 56.5%
    }
}







반응형