不使用浮动使图像填充保持垂直高度

时间:2015-05-05 18:32:18

标签: html css responsive-design

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
div {box-sizing: border-box; color: white;}

img {margin: 0px; padding: 0px; height: 100%; width: 100%;}

h2 {float: left; display: block; padding-bottom: 10px; font: 14px sans-serif; background-color: red; width: 100%; margin: 0px;}

div.left {background-color: black; border-right:solid 5px white; float: left; width: 66.66%; padding: 10px; overflow: auto; }
div.right {background-color: green; border-left:solid 5px white; float: right; width: 33.33%; padding: 10px; overflow: auto;}
</style>

<div class="container" style="width: 100%; background-color: red;">
    
    <div class="left" aspect="2">
         <h2>this a header</h2>
        
         <img src="http://imagesofrmnp.com/images/300/Longs-Illuminated.jpg" width="100%" height="100%" />
        

    </div>
    
    <div class="right" aspect="1">
        <h2>this a header</h2>
         
        <img src="https://d13yacurqjgara.cloudfront.net/users/31752/screenshots/2049807/school-house_1x.png" width="100%" height="100%" />
        
    </div>

</div>


<script type="text/javascript">
     
    
    function FixAspect()
    {
        $("div[aspect]").css("height", function() { return Math.round(this.getBoundingClientRect().width / $(this).attr("aspect")); });
    }
    
    setInterval(FixAspect, 50);
</script>

你可以看到,通过使用高度100%,图像溢出,因为标题占用了100%的一部分。所以基本上它必须填补剩余的空间。

我知道我可以用js计算标头占用多少空间,但css解决方案会更好。

我试过浮动标题,但没有帮助。

请注意,不必保留图像的宽高比。

1 个答案:

答案 0 :(得分:0)

HTML

<div class="container" style="width: 100%; background-color: red;">

    <div class="left" aspect="2">
    </div>

    <div class="right" aspect="1">
        <h2>this a test header</h2>
    </div>

</div>

CSS:

div {box-sizing: border-box; color: white;}

        img {margin: 0px; padding: 0px;}

        div.left {background-color: black; border-right:solid 10px orange; float: left; width: 66.6666%;  }
        div.right {background-color: green; border-left:solid 10px orange; float: right; width: 33.3333%;  overflow: hidden;}
        div.right{

            background-image: url("http://promundoglobal.org/wp-content/uploads/2014/12/images.jpg");
            height: 300px;
            width: 300px;
        }

https://jsfiddle.net/Loeapap1/12/