仅在较大时拉伸图像

时间:2013-05-10 18:46:29

标签: css

我正在尝试刷新css并想知道这是否仅适用于css:

假设我想要在100x100像素div标签中显示图像。我不确定图像会是什么,但如果它小于100x100像素,我希望它将图像居中。如果图像较大,我希望它缩小到窗口的大小。

例如,如果它更大:

enter image description here

如果它更小:

enter image description here

单独使用css是否可行?

2 个答案:

答案 0 :(得分:3)

当然,不是问题。试试这个:

<强> CSS

div {
    display: table-cell;
    vertical-align: middle;
    border:1px solid #999;
    width:100px;
    height:100px;
    text-align:center;
    font-size:0;
}
img {
    max-width:100px;
}

<强> HTML

<div>
    <img src="http://www.placekitten.com/200/200" />
</div>

<div>
    <img src="http://www.placekitten.com/50/50" />
</div>

jsFiddle example 两张图片,一张50x50,另一张200x200

答案 1 :(得分:1)

试试这个:

CSS

div {
  max-width: 100px;
  max-height: 100px;
}

img {
  width: 100px;
  display: block;
  margin-left: auto;
  margin-right: auto;
  border: solid 1px #000;
}

HTML

<div>
<img src="image source1" alt="enter image description here">
</div>
<br>
<div>
<img src="image source2" alt="enter image description here">
</div>

JSFiddle

顶部图像最初为100像素×100像素,底部最初为75像素×75像素。

修改

哎呀,把我的CSS倒在了小提琴上。它现在已更新。