1

http://jsfiddle.net/3qMnM/1/

HTML

<div class="info-panel"></div>
<div class="image">
    <img src="http://placehold.it/960x1400">
</div>

CSS

.image {
height: 100%;
width: auto;
margin-right: 200px;
}


.info-panel {
position: fixed;
width: 200px;
height: 100%;
background-color: red;
right: 0px;
}

我正在尝试动态缩小图像(从不放大)以适应图像 div(不裁剪),它的高度(100%)和宽度(设置为自动)是可变的。图像还需要居中(垂直和水平)并在顶部和底部具有相等的几个像素的填充。

正如您在小提琴中看到的那样,图像容器旁边有一个信息面板,但我不确定这是否相关。

我的陈述有意义吗?

谢谢,我已经花了太多时间来试验这个了!:/

4

3 回答 3

2

If I understand correctly, you want something like this.

It scales down if the image is too large, but keeps the original size when it fits inside the window. In other words, it never scales up - only down.

It is a combination of CSS and some jQuery:

This short JS centers the image vertically:

function verticallyCenterImage(){
    var $img = $('.image img'),
        windowHeight = $(window).outerHeight();

    if($img.height() < windowHeight){
        var delta = windowHeight - $img.height();
        $img.css('margin-top', (delta / 2) + 'px');
    }else{
        $img.attr('style', '');
    }
}

And this line of CSS keeps the image centered horizontally:

.image {
    padding-right: 200px;
    text-align: center;    /* <- this one */
    max-height: 100%;
    overflow: hidden;
}

And to keep the original size of the image, I just set the max height and width on the img inside the .image class, like so:

.image img {
    max-width: 96%;
    max-height: 96%;
    margin: 2%;
}

You can adjust the size and margins to your needs, just remember to keep them in relation too each other :)

于 2013-05-22T22:54:29.247 回答
0

您正在将 px 与 % 混合。如果您只想通过 CSS 实现,则需要对两个宽度都使用 % :

.image {
    width: 85%;
}

.image img {
    width: 100%;
}

.info-panel {
    position: fixed;
    width: 15%;
    height: 100%;
    background-color: red;
    right: 0px;
}

...否则,您必须使用 JS 计算左侧的当前可用宽度并将其分配给 .image div:

HTML

<div class="info-panel"></div>
<div class="image">
    <img src="http://placehold.it/960x1400" />
</div>

CSS

.image {
    min-height: 600px;
    width: auto;
}

.image img {
    width: 100%;
}

.info-panel {
    position: fixed;
    width: 200px;
    height: 100%;
    background-color: red;
    right: 0px;
}

JS (jQuery)

$(document).ready(function() {
    $('.image')
        .css('min-height', 'auto')
        .height($(window).height())
        .width($(window).width() - $('.info-panel').width())
    ;
});
于 2013-05-22T21:57:53.680 回答
0

这里讨论的一些技术可能对你有用: http ://css-tricks.com/centering-in-the-unknown/

诀窍是使用表格元素或 CSS 2.1 表格显示。

编辑:这里有更多方法:http ://www.vanseodesign.com/css/vertical-centering/

于 2013-05-22T22:12:23.913 回答