Để div full height viewport, dùng đơn vị vh (viewport height) hoặc flexbox trên html/body.
Cách 1: vh unit (đơn giản nhất)
<!DOCTYPE html>
<html>
<head>
<style>
html, body { margin: 0; height: 100vh; }
.full-height {
height: 100vh;
background: mistyrose;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
font-size: 2rem;
}
</style>
</head>
<body>
<div class="full-height">100% Chiều Cao Viewport!</div>
</body>
</html>
Cách 2: Flexbox trên body
<style>
html, body {
margin: 0;
height: 100vh;
display: flex;
flex-direction: row;
justify-content: space-around;
}
.panel {
width: 40%;
height: 100vh;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.5rem;
}
</style>
<body>
<div class="panel" style="background: #ffe4e1;">Panel 1</div>
<div class="panel" style="background: #e0ffff;">Panel 2</div>
<div class="panel">Panel 3</div>
<div class="panel">Panel 4</div>
</body>
Kết quả
- Cách 1: 1 div full màn hình, nội dung căn giữa
- Cách 2: 4 panel ngang bằng nhau, mỗi panel full height, nội dung căn giữa
Lưu ý quan trọng
100vh= 100% chiều cao viewport (kể cả thanh address bar mobile)- Trên mobile, thanh địa chỉ ẩn/hiện làm thay đổi vh → dùng
100dvh(dynamic viewport height) nếu hỗ trợ - Cần
html, body { margin: 0; height: 100%; }cho cách % truyền thống