frontend

Viewport (CSS), 추가정보

하리하링웹 2024. 4. 11. 21:45

Viewport size

viewport의 size는 변할 수 있다.

  • 브라우저 창 크기 조절
  • 모바일 가로, 세로, etc..
  • 키보드 창 켜짐

 

자바스크립트에서 viewport size를 받는법

document.documentElement.clientWidth; /* 1200 */
window.innerWidth; /* 1200 */
window.outerWidth; /* 1200 */

document.documentElement.clientHeight; /* 800 */
window.innerHeight; /* 800 */
window.outerHeight; /* 900 */
  • document.documentElement.clientWidth: document의 가로 px값이며 패딩은 포함되지만 마진, 테두리, 세로 스크롤 바 크기는 포함되지 않는다.
  • window.innerWidth: 스크롤바가 포함된 브라우저의 가로 크기이다
  • window.outerWidth: 브라우저의 전체 창 가로 크기이다 크롬의 경우 innerWidth와 같다
    • 크롬에서 outerHeight의 경우 innerHeight와 다른 것을 확인할 수 있다. 이는 주소창, 북마크 같은 값도 outerHeight에 포함되기 때문이다.
    • 브라우저마다 값이 다를 수 있다. 예를들어 주소창이 가로에 있는 브라우저의 경우 innerWidth와 outerWidth가 다를 수 있다.

zoom의 경우도 아래처럼 브라우저별로 다른 결과 값을 줄 수 있다.

document.documentElement.clientWidth; /* 800 */
window.innerWidth; /* 800 */
window.outerWidth; /* 800 in Firefox, 1200 in chrome */

document.documentElement.clientHeight; /* 533 */
window.innerHeight; /* 533 */
window.outerHeight; /* 596 in Firefox, 900 in chrome */

크롬의 경우 outerValue는 zoom을 하더라도 scale이 변하지 않은 초기 값으로 유지된다.

 

Viewport CSS

  • [number]vh,vw
  • layout viewport의 number% 값이다. 예를들어 1vh는 1%의 viewport height 값을 나타낸다.
  • iframe
    @media screen and (min-width: 500px) {
      p {
        color: red;
      }
    }
    
  • iframe의 viewport는 iframe 자체의 inner width, height를 따라간다. 예를들어 부모의 innerWidth가 1200px이고 iframe의 크기가 50vw로 설정되어 있다면 iframe의 viewport는 600px이며 iframe에서 사용하는 1vw는 6px이다.

위와 같은 코드가 있을 때 윈도우의 크기는 변하지 않더라도 iframe의 inner width가 500px 이상이면 color가 적용되게된다.

  • SVG
    <svg height="300" width="400"></svg>
    
    위코드에서 svg는 400의 viewport width와 300의 hieght 값을 가진다.
  • svg 또한 iframe과 같은 rule을 따른다.

 

Media Query

if문처럼 조건과 일치할 때 내부 css를 실행시켜준다.

[문법]

@media (조건) {
  css
}

[예시]

  • 800px 이하일경우 background-color가 red
@media (max-width: 800px) {
  .small-red {
    background-color: red;
  }
}

or

@media (width <= 800px) {
  /* … */
}
  • and, or,not 연산도 가능하다.
@media (min-width:768px) and (max-width:1024px) { … } // 뷰포트 너비가 768px 이상 '그리고' 1024px 이하이면 실행

@media (width:768px), (width:1024px) { … } // 뷰포트 너비가 768px 이거나 '또는' 1024px 이면 실행

@media not (min-width:768px) and (max-width:1024px) { … } // 뷰포트 너비가 768px 이상 '그리고' 1024px 이하가 '아니면' 실행