使图像居中并填充div而不会失真

时间:2013-05-12 18:54:33

标签: css html centering stretching

我一直在寻找几乎的解决方案,我认为应该非常简单,但无法弄明白。 (注意 - 我现在正处于学习CSS的初级阶段)

我有一个图像放在页面上。中心水平/垂直。在div容器中,窗口高度和宽度的80%。我希望图像能够拉伸以填充div的高度或宽度,基于最小值。

我确信这对大多数人来说很简单,但是我只是在学习。任何方向都很棒。

我创建了一个插图,以防我解释得不够好: enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个http://jsfiddle.net/David_Knowles/ddh2k/

这可以满足您的大部分需求。如果您只想在屏幕高度降低到图像固有高度时将图像设置为可用高度的80%,则需要添加一些额外的javascript。

<body>
<div id="container">
        <img src="http://dummyimage.com/600x400/000/fff.jpg" alt="apropriate alt text">
</div>
</body>

html,
body{
    height:100%;
    width:100%;
    margin:0;
    padding:0;
    background-color: #eee;
}
#container{
    margin: auto;
    width:100%;
    height:100%;
    text-align:center;
    font-size:0;
    white-space:nowrap;
    background:#aae;
}
#container:before{
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
}
img {
    width:80%;
    height:auto;
    display:inline-block;
    vertical-align:middle;
    background:#fff;
}