Đơ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ĩa | Ví dụ dùng |
|---|---|---|
vh | 1% viewport height | Fullscreen hero: height: 100vh |
vw | 1% viewport width | Responsive font: font-size: 5vw |
vmin | 1% min(viewport width, height) | Square element: width: 50vmin; height: 50vmin |
vmax | 1% 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.
100vhcó thể gây overflow khi address bar hiện. Dùngheight: 100%trênhtml, bodyhoặc CSSenv(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 */
}