Not able to fix iframe height

2019-09-06 23:59发布

问题:

I have the following sample code:

<style type="text/css">
.div_class
{
position:absolute;
border:1px solid blue;
left:50%;
margin-left:-375px;
margin-top:100px;
height:300px;
width:500px;
overflow:hidden;
}
.iframe_class
{
position:relative;
border:1px solid red;
height:100%;
margin-left:-218px;
margin-top:-110px;
}
</style>
<div class="div_class">
<iframe src="http://www.w3schools.com/" class="iframe_class" />
</div>

In the code above, a div encloses an iframe of which only a part (from position [x=218,y=110]) has to be displayed. As you can see, I have placed height:100% for iframe which means it takes the height of the div. This is where the problem starts. The iframe is cropped. ie. the iframe's right border and bottom border have moved with the repositioning.

What I want: Even after the repositioning of the iframe, I want the right border and the bottom border to coincide with the right border and bottom border of the div respectively. How do I do it?

Note:

  1. http://www.w3schools.com/ is taken just as an example. In my actual code, the iframe source will be decided by a PHP script.
  2. I cannot set the iframe height to 218+document_height_of_iframe_src because as I said the src is dynamically decided by a backend script. So document_height_of_iframe_src will be unknown to me. Same is the case with document_width_of_iframe_src.
  3. I have to accomplish all this without using JavaScript.

Thanks in advance...

回答1:

Margin and border styles aren't included in an element width/height. So they have their own layout space. To fix it, add a bottom padding to the iframe_class's container (the div_class) like this.

.div_class
{
position:absolute;
border:1px solid blue;
left:50%;
margin-left:-375px;
margin-top:100px;
height:300px;
width:500px;
overflow:hidden;
/*added to compensate iframe border (top+bottom)*/
padding-bottom:2px;
}
.iframe_class
{
position:relative;
border:1px solid red;
height:100%;
/*removed. messed the layout.
margin-left:-218px;
margin-top:-110px;
*/
}


标签: css html iframe