中心图像到div的中心

时间:2012-01-09 22:42:06

标签: html css

所以,假设我有一个div和一个像这样的图像

<div id="image_wrapper">
    <img src="image.jpg" />
</div>

现在让我们说css是这样的:

#image_wrapper{
    width:100px;
    height:120px;
    overflow:hidden;
}
img{
    max-width:100px;
    max-height:120px;
}

现在我的图像可以是任何类型的大小,并且最大宽度或高度角色会几乎完美地调整大小但是我需要图像来完全填充image_wrapper,现在我知道它听起来很不可能但是我看到了facebok做了什么他们的形象,他们只是切出边缘,这样使所有图像看起来都很完美,那么他们是如何做到的呢?

编辑只要能胜任,Javascript或php帮助就完全可以了。

5 个答案:

答案 0 :(得分:4)

如果您的#image_wrapper不需要特定的高度或宽高比,您可以从响应式网页设计移动中获取灵感,并允许图像将其宽度缩放到100其含元素的百分比:

考虑这个CSS Desk example

<强> HTML:

<div id="image_wrapper">
    <img src="image.jpg" />
</div>

<强> CSS:

#image_wrapper {
    background-color: #000;
    padding: 5px;
    text-align: center;
    width: 500px;
}

img {
    width: 100%;
}

尝试更改#image_wrapper的宽度,并注意图像如何符合新尺寸。

答案 1 :(得分:1)

将CSS3 background-sizeno-repeat center centerdemo)一起使用。

#image_wrapper {
    height:120px;
    width:100px;
    background:no-repeat center center url(image.png);
    background-size:contain;
}

#image_wrapper > img {
    display:none;
}

如果您想使用JavaScript,请尝试:

<style>
.image_wrapper {
    height:190px;
    width:1000px;
    border:1px solid;
    background:no-repeat center center;
    background-image:url(science.png);
    background-size:contain;
}
</style>

<script type="text/javascript">

function getStyle(el,cssAttribute){
    if(window.getComputedStyle)
        return window.getComputedStyle(el, "").getPropertyValue(cssAttribute);
    else if(document.getElementById(strID).currentStyle)
        return document.getElementById(strID).currentStyle.getAttribute(cssAttribute,false);
    else
        return el.style.getAttribute(cssAttribute,false);
}

window.addEventListener("DOMContentLoaded",function(){
    var w;
    for(var i = 0; w = document.querySelectorAll(".image_wrapper")[i];++i){
        var backgroundSize = '';
        if(w.firstChild.width < parseInt(getStyle(w,"width")))
            backgroundSize += 'auto ';
        if(w.firstChild.height < parseInt(getStyle(w,"height")))
            backgroundSize += 'auto ';
        if(backgroundSize === '')
            backgroundSize = 'contain';
        w.style.backgroundSize = backgroundSize;
        w.style.backgroundImage = 'url('+w.firstChild.src+')';
        w.firstChild.style.display = 'none';
    }
},true);
</script>

这会将每个<div class="image_wrapper"><img src="..."/></div>更改为精美的图片包装。

答案 2 :(得分:0)

我无法改进this answer。简而言之:使用表格。

答案 3 :(得分:0)

如果您不想沿着js路走下去,那么用php完成它是一种非常简单的方法。我建议您安装phpThumb。它负责调整缩放和过滤图像的缩略图(和其他东西),这看起来就像你想要在这里实现的那样。您可以将所有参数传递给脚本(请参阅:Demo Page)。它有一个叫缩放裁剪(zc),它可以放大图像,使其适合您指定的尺寸,并在中心内进行裁剪。这完全符合您的描述。因此,只需将此URL用于div中的图像。

http://URLTOPHPTHUMB.PHP?src=SOURCEOFYOURIMAGE&w=120&h=100&zc=1

答案 4 :(得分:-1)

如果没有javascript / jquery,你无法做到这一点。

http://ditio.net/2010/01/02/jquery-image-resize-plugin/

更新,这里有一个例子:

http://webdesignledger.com/tutorials/create-a-resizable-image-grid-with-jquery