zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

How to achieve height auto-adaptation when introducing iframe videos on a website?

I believe many friends encounter a headache when writing a blog. When trying to embed an external video using iframe, the size is always problematic. The width can be fixed at 100%, but the height needs to be represented by the actual height, such as 100px, 200px, and so on.

However, here comes the problem. The height of the video remains consistent across different page widths, which causes a troublesome issue.

Take a look at the two images below:

Desktop

image

Mobile

image

Clearly, the video that displays correctly on desktop appears misaligned in terms of height on mobile, which is not aesthetically pleasing.

To solve this problem, media queries can be used, but it is obviously time-consuming and not so perfect.

In fact, it is very simple and only requires less than 10 lines of code to achieve a perfect solution.

  1. Include jQuery (usually websites already have this file).

  2. Add a piece of JavaScript code, preferably placed at the bottom of the website, just before </body>.

$('iframe').wrap('<p class="iframe"></p>')
  1. Add the following code at the bottom of the CSS file:
.iframe{
  position: relative;
  padding-bottom: 56.25%;
  height: 0;
  overflow: hidden;
}
.iframe iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

Now, when visiting a webpage with an iframe video, regardless of the width changes, the height can adapt to the video.

For example, you can see the effect on this webpage: https://imhan.cn/posts/20210507.html

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.