📅  最后修改于: 2023-12-03 15:00:04.783000             🧑  作者: Mango
When working with iframes, often times we want to fit them into a container div so that they fit seamlessly into the layout. This can be accomplished with a little bit of CSS using the padding-bottom
hack.
The padding-bottom
hack is a technique used to force a container to maintain its aspect ratio. It's used in combination with position: relative;
and position: absolute;
to create a space at the bottom of the container that is equal to the aspect ratio of the content that is being displayed.
Let's say we have the following HTML markup:
<div class="container">
<iframe src="https://www.example.com"></iframe>
</div>
And our CSS looks like this:
.container {
position: relative;
width: 100%;
}
.container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
This will make the iframe fill the entire container, but it will also stretch the aspect ratio of the content inside the iframe. To fix this, we'll add the padding-bottom
hack to our container
class:
.container {
position: relative;
width: 100%;
padding-bottom: 56.25%;
}
.container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
The padding-bottom: 56.25%;
value is calculated by taking the aspect ratio (in this case, a typical YouTube video is 16:9) and dividing the height (9) by the width (16) and multiplying by 100. This gives us the percentage value we need to use for the padding-bottom
.
With this CSS, the container will maintain the aspect ratio of the content inside the iframe and fit seamlessly into your layout.
The padding-bottom
hack is a useful technique to use when you want to fit an iframe into a container without distorting the aspect ratio of the content. With a little bit of math, you can easily calculate the percentage value needed for the padding-bottom
to ensure that your iframe looks great on any device.