zishu's blog

zishu's blog

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

How to achieve height auto-adjustment when introducing iframe video on a website?

I believe many bloggers have encountered a headache-inducing problem when writing blog posts. They want to embed an external video using an iframe, but the size is always an issue. 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 can be quite troublesome.

Take a look at the following two images:

Desktop

image

Mobile

image

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

To solve this problem, you can use media queries, but it is time-consuming and not so perfect.

In fact, it's quite simple. You only need less than 10 lines of code to achieve a perfect solution.

  1. Include jQuery (most websites already have this file by default).

  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 you visit a webpage with an iframe video, regardless of the width changes, the height can adapt to the video perfectly.

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.