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
Mobile
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.
-
Include jQuery (usually websites already have this file).
-
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 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