Подтвердить что ты не робот

Содержат изображение в div?

Я хочу содержать изображение в 250 х 250 div, заставляя изображение изменять размер, но не растягиваться. Как я могу это сделать? Кстати, изображение, как правило, будет больше, чем сам div, поэтому изменение размера происходит в изображении.

<div id = "container">
  <img src = "whatever" />
</div>

#container { width:250px; height:250px; border:1px solid #000; }

Здесь jsfiddle, который кто-то может редактировать:

http://jsfiddle.net/rV77g/

4b9b3361

Ответ 1

Используйте максимальную ширину и максимальную высоту. Он сохранит соотношение сторон

#container img 
{
 max-width: 250px;
 max-height: 250px;
}

http://jsfiddle.net/rV77g/

Ответ 2

object-fit, ведет себя как background-size, решая проблему масштабирования изображений вверх и вниз для соответствия.

Объектно-ориентированное свойство CSS указывает, как содержимое замененного элемента должно быть установлено в поле, установленное его используемой высотой и шириной.

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

Edge еще не поддерживается: https://caniuse.com/#search=object-fit


Обновление до 2016 года

Появились новые полиполки, так как я последний раз смотрел на этот ответ! https://github.com/bfred-it/object-fit-images/#alternative-solutions


Обновление Nov 2015

Я не тестировал это достаточно хорошо в IE изначально и нашел теперь, что он не работает для меня вообще в IE. Очевидно, что край IE не поддерживается: https://github.com/anselmh/object-fit/issues/45

<sigh> IE: (


enter image description here

.cover img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    overflow: hidden;
}

Я опубликовал сравнение некоторых методов в фрагменте SO ниже (открыть и запустить.. он длинный, поэтому я спрятал его по умолчанию):

document.addEventListener('DOMContentLoaded', function() {
  objectFit.polyfill({
    selector: '.cover',
    fittype: 'cover'
  });
  objectFit.polyfill({
    selector: '.contain',
    fittype: 'contain'
  });
});
.no-tricks,
.cover,
.contain,
.min-max-height, 
.no-object-fit,
.no-cover {
  width: 150px;
  height: 150px;
  overflow: hidden;
  outline: 1px solid gray;
  background-color: whitesmoke;
  text-align: center;

}
.no-tricks img,
.cover img,
.contain img,
.min-max-height, img 
.warp img,
.no-cover img {
    outline: 1px solid black;
}

.cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  overflow: hidden;
}
.contain img {
  width: 100%;
  height: 100%;
  object-fit: cotain;
  overflow: hidden;
}

.no-object-fit img {
  width: 100%;
  height: 100%;
}

.min-max-height img {
  max-height: 100%;
  min-height: 100%;
}

.no-cover img {
  width: 100%;
  height: auto;
}

.raw {
  outline: 1px solid magenta;
}
<code>object-fit: cover;</code>
<div class="cover">
  <img src="http://upload.wikimedia.org/wikipedia/commons/6/6d/Circle_radius_w.svg">
</div>

<hr>

<code>object-fit: contain;</code>
<div class="contain">
  <img src="http://upload.wikimedia.org/wikipedia/commons/6/6d/Circle_radius_w.svg">
</div>

<hr>

 <code>no tricks (image is cropped, not at all resized)</code>
<div class="no-tricks">
  <img src="http://upload.wikimedia.org/wikipedia/commons/6/6d/Circle_radius_w.svg">
</div>

<hr>

 <code>without object-fit</code>
<div class="no-object-fit">
  <img src="http://upload.wikimedia.org/wikipedia/commons/6/6d/Circle_radius_w.svg">
</div>

<hr>

 <code>min-max-height (works if you know the src is landscape, crops from the left)</code>
<div class="min-max-height">
  <img src="http://upload.wikimedia.org/wikipedia/commons/6/6d/Circle_radius_w.svg">
</div>

<hr>

 <code>height auto - doesn't cover</code>
<div class="no-cover">
  <img src="http://upload.wikimedia.org/wikipedia/commons/6/6d/Circle_radius_w.svg">
</div>

<hr>

<p>Raw image (note the aspect ratio):</p>
<img class="raw" src="http://upload.wikimedia.org/wikipedia/commons/6/6d/Circle_radius_w.svg">

<script src="https://raw.githubusercontent.com/anselmh/object-fit/master/dist/polyfill.object-fit.js">

Ответ 3

Вы должны создать стиль, подобный этому

#container img{width:100%;}

и контейнер со скрытым переполнением:

#container{width:250px; height:250px; overflow:hidden; border:1px solid #000;} 

Ответ 4

Поскольку вы не хотите растягивать (все остальные ответы игнорируют это), вы можете просто установить max-width и max-height, как в моем jsFiddle edit.

#container img {
    max-height: 250px;
    max-width: 250px;
} 

См. мой пример с изображением, которое не является квадратом, оно не растягивается

Ответ 5

Вот javascript, который я написал, чтобы сделать именно это.

function ImageTile(parentdiv, imagediv) {
imagediv.style.position = 'absolute';

function load(image) {
    //
    // Reset to auto so that when the load happens it resizes to fit our image and that
    // way we can tell what size our image is. If we don't do that then it uses the last used
    // values to auto-size our image and we don't know what the actual size of the image is.
    //
    imagediv.style.height = "auto";
    imagediv.style.width = "auto";
    imagediv.style.top = 0;
    imagediv.style.left = 0;

    imagediv.src = image;
}

//bind load event (need to wait for it to finish loading the image)
imagediv.onload = function() {
    var vpWidth = parentdiv.clientWidth;
    var vpHeight = parentdiv.clientHeight;
    var imgWidth = this.clientWidth;
    var imgHeight = this.clientHeight;

    if (imgHeight > imgWidth) {
        this.style.height = vpHeight + 'px';
        var width = ((imgWidth/imgHeight) * vpHeight);
        this.style.width = width + 'px';
        this.style.left = ((vpWidth - width)/2) + 'px';
    } else {
        this.style.width = vpWidth + 'px';
        var height = ((imgHeight/imgWidth) * vpWidth);
        this.style.height = height + 'px';
        this.style.top = ((vpHeight - height)/2) + 'px';
    }
};

return {
    "load": load
};

}

И для его использования просто сделайте что-то вроде этого:

 var tile1 = ImageTile(document.documentElement, document.getElementById("tile1"));
 tile1.load(url);

Я использую это для слайд-шоу, в котором у меня есть две из этих "плиток", и я угасаю один, а другой. Загрузка выполняется на "плитке", которая не видна, чтобы избежать резкого визуального воздействия возврат стиля обратно к "авто".

Ответ 6

  <div id ="container">
    <img src = "http://animalia-life.com/data_images/duck/duck9.jpg"/>
#container img {
        max-width:250px;
        max-height:250px;
        width: 250px;
        height: 250px;
        border:1px solid #000;
    }

img потеряет соотношение сторон

Ответ 7

#container img{
 height:100%;
 width:100%;   
}