在一个框架内刻录并居中图像

时间:2014-05-22 16:42:04

标签: javascript html css

给定一个任意宽高比的div,最好的方法是放置和设置图像(也有任意宽高比),以便:

  1. 既有铭文又有中心
  2. 使用相对值设置其尺寸和位置,以便在帧均匀缩放时图像将保持内切并自动居中(仅在初始插入图像时才需要javascript,或者如果帧的宽高比发生变化)< / LI>
  3. 最小化额外标记
  4. 这是我们想要的结果:

    example of inscribe and centered

    Here's a fiddle template,这只是:

    标记

    Should pillarbox
    <div class="frame">
        <img src="http://www.placekitten.com/200/300" />
    </div>
    
    Should letterbox
    <div class="frame">
        <img src="http://www.placekitten.com/300/200" />
    </div>
    

    CSS

    .frame {
        width: 200px;
        height: 200px;
        border: 2px solid black;
        margin: 10px 0px 100px 0;
    }
    

3 个答案:

答案 0 :(得分:4)

你可以尝试这样的事情:updated fiddle

.frame {
    width: 200px;
    height: 200px;
    border: 2px solid black;
    margin: 10px 0px 100px 0;
    position: relative; /* added */
}

img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    margin: auto;
    top: 0; left: 0; bottom: 0; right: 0;
} 

答案 1 :(得分:2)

合并Adrift's css

.frame {
    width: 400px;
    height: 400px;
    border: 2px solid black;
    margin: 10px 0px 100px 0;
    position: relative; /* added */
}

img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    margin: auto;
    top: 0; left: 0; bottom: 0; right: 0;
} 

使用javascript

var inscribe = function(img, frame) {
    var imgRatio = img.width / img.height;
    var frameRatio = frame.offsetWidth / frame.offsetHeight;

    if (imgRatio > frameRatio) { // image is wider than frame; letterbox
        img.style.width = '100%';
        img.style.height = 'auto';
    } else {                     // image is taller than frame; pillarbox
        img.style.width = 'auto';
        img.style.height = '100%';
    }
}

可以满足所有要求。

http://jsfiddle.net/PBPkh/4/

答案 2 :(得分:1)

如果你能摆脱<img />元素,你也可以通过背景图像实现这一点。

背景大小 上有一个名为 包含 的css属性,可以完成这项任务:

.background{
   background-size: contain;
}

如果您希望将图像居中,只需添加:

background-position: center center;