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

Tại sao iframe không cho phép absolute positioning height/width?

<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

  1. Tạo một <div> bao ngoài (wrapper) với position: absolute và đặt top, left, right, bottom.
  2. 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ỳ.