Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Thiết lập viewport height/width trong CSS (vh, vw)

Đơn vị viewport cho phép kích thước tương đối so với **kích thước khung nhìn (viewport)** của trình duyệt.

Viewport Height (vh)

h1 {
  font-size: 4.0vh; /* 4% chiều cao viewport */
}

1vh = 1% chiều cao viewport.

Viewport Width (vw)

h1 {
  font-size: 5.5vw; /* 5.5% chiều rộng viewport */
}

1vw = 1% chiều rộng viewport.

Các đơn vị viewport liên quan

Đơn vịĐịnh nghĩaVí dụ dùng
vh1% viewport heightFullscreen hero: height: 100vh
vw1% viewport widthResponsive font: font-size: 5vw
vmin1% min(viewport width, height)Square element: width: 50vmin; height: 50vmin
vmax1% max(viewport width, height)Fullscreen overlay lớn nhất

Lưu ý quan trọng

  • Mobile browser chrome (address bar): Trên mobile, viewport height thay đổi khi address bar ẩn/hiện. 100vh có thể gây overflow khi address bar hiện. Dùng height: 100% trên html, body hoặc CSS env(safe-area-inset-bottom).
  • Scrollbar: Trên desktop, viewport width bao gồm scrollbar (nếu overlay scrollbar thì không).
  • Font-size vw: Cực nhỏ trên mobile, cực lớn trên desktop. Kết hợp clamp(): font-size: clamp(1rem, 3vw, 2rem).

Ví dụ Responsive Typography với clamp

h1 {
  font-size: clamp(1.5rem, 5vw, 3rem); /* min 1.5rem, preferred 5vw, max 3rem */
}