<iframe> là replaced element (phần tử được thay thế), hành vi khác với non-replaced element như <div>. Replaced element không hỗ trợ đặt đồng thời top/bottom hoặc left/right để co giãn (stretch) theo cả hai chiều.
Giải pháp: Dùng wrapper div
- Tạo một
<div>bao ngoài (wrapper) vớiposition: absolutevà đặttop,left,right,bottom. - Cho
<iframe>bên trong wrapper với kích thước 100%.
Mã CSS
.iframe-wrapper {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
}
.iframe-wrapper iframe {
width: 100%;
height: 100%;
border: none;
}
HTML
<div class="iframe-wrapper"> <iframe src="https://example.com"></iframe> </div>
Cách này hoạt động trên mọi trình duyệt và cho phép iframe lấp đầy vùng container tuyệt đối bất kỳ.