Thuộc tính window.innerWidth trả về chiều rộng khu vực hiển thị nội dung (viewport) của cửa sổ, không tính giao diện trình duyệt.
Cú pháp
window.innerWidth
Ví dụ
<!DOCTYPE html>
<html>
<style>
body { color: #000; height: 100vh; background-color: #8BC6EC; background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%); text-align: center; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
.show { font-size: 1.2rem; }
</style>
<body>
<h1>Demo window.innerWidth</h1>
<button onclick="showInnerWidth()" class="btn">Xem chiều rộng viewport</button>
<div class="show"></div>
<script>
function showInnerWidth() {
document.querySelector('.show').innerHTML = 'Chiều rộng viewport (innerWidth): ' + window.innerWidth + 'px';
}
</script>
</body>
</html>
Kết quả
Nhấn nút → hiển thị chiều rộng vùng hiển thị web (trừ UI browser).
Ứng dụng chính: Responsive breakpoints, CSS media query trong JS, canvas/game resize, layout tính toán. Cặp đôi với innerHeight.