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
Mobile
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.
-
Include jQuery (most websites already have this file by default).
-
Add a piece of JavaScript code, preferably placed at the bottom of the website, just before
</body>
.
$('iframe').wrap('<p class="iframe"></p>')
- 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