이미지의 종횡비를 유지하면서 <div>를 채우기 위해 이미지를 어떻게 늘립니까? 여부를 알

이 이미지를 넘치 <div>거나 이미지를 기울이지 않고 가능한 최대 크기로 늘려야합니다.

이미지의 종횡비를 예측할 수 없으므로 사용할지 여부를 알 수있는 방법이 없습니다.

<img src="url" style="width: 100%;">

또는

<img src="url" style="height: 100%;">

style = “width : 100 %; height : 100 %;”)를 모두 사용할 수 없으므로 이미지에 맞게 이미지가 늘어나 기 때문입니다 <div>.

<div>화면 크기에 따라 크기가 설정되어 있으며 예측할 수 없습니다.



답변

2016 업데이트 :

최신 브라우저는 훨씬 더 잘 작동합니다. 이미지 너비를 100 % ( 데모 ) 로 설정하기 만하면 됩니다.

.container img {
   width: 100%;
}

종횡비를 모르기 때문에 일부 스크립팅을 사용해야합니다. 다음은 jQuery ( demo )로 수행하는 방법입니다 .

CSS

.container {
    width: 40%;
    height: 40%;
    background: #444;
    margin: 0 auto;
}
.container img.wide {
    max-width: 100%;
    max-height: 100%;
    height: auto;
}
.container img.tall {
    max-height: 100%;
    max-width: 100%;
    width: auto;
}​

HTML

<div class="container">
 <img src="http://i48.tinypic.com/wrltuc.jpg" />
</div>
<br />
<br />
<div class="container">
 <img src="http://i47.tinypic.com/i1bek8.jpg" />
</div>

스크립트

$(window).load(function(){
 $('.container').find('img').each(function(){
  var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
  $(this).addClass(imgClass);
 })
})

답변

CSSand 만 사용 하여이 작업을 수행하는 훨씬 쉬운 방법이 있습니다 HTML.

HTML :

<div class="fill"></div>

CSS :

.fill {
    overflow: hidden;
    background-size: cover;
    background-position: center;
    background-image: url('path/to/image.jpg');
}

이미지를 배경으로 배치하고 div왜곡없이 크기 에 맞게 이미지를 늘립니다 .


답변

완벽한 솔루션은 아니지만이 CSS가 도움이 될 수 있습니다. 줌은이 코드를 작동시키는 원인이며, 이론적으로 작은 이미지에 이상적으로 작동하려면 요소가 무한해야합니다. 그러나 대부분의 경우 2, 4 또는 8이 잘 작동합니다.

#myImage {
    zoom: 2;  //increase if you have very small images

    display: block;
    margin: auto;

    height: auto;
    max-height: 100%;

    width: auto;
    max-width: 100%;
}

답변

가능하면 배경 이미지를 사용하고을 설정하십시오 background-size: cover. 그러면 배경이 전체 요소를 덮게됩니다.

CSS

div {
  background-image: url(path/to/your/image.png);
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-size: cover;
}

인라인 이미지를 사용하는 데 어려움이 있다면 몇 가지 옵션이 있습니다. 먼저

객체 적합

이 속성은 이미지, 비디오 및와 유사한 다른 개체에 적용됩니다 background-size: cover.

CSS

img {
  object-fit: cover;
}

슬프게도 브라우저 지원 은 IE 11 버전까지는 전혀 지원하지 않습니다. 다음 옵션은 jQuery를 사용합니다.

CSS + jQuery

HTML

<div>
  <img src="image.png" class="cover-image">
</div>

CSS

div {
  height: 8em;
  width: 15em;
}

커스텀 jQuery 플러그인

(function ($) {
  $.fn.coverImage = function(contain) {
    this.each(function() {
      var $this = $(this),
        src = $this.get(0).src,
        $wrapper = $this.parent();

      if (contain) {
        $wrapper.css({
          'background': 'url(' + src + ') 50% 50%/contain no-repeat'
        });
      } else {
        $wrapper.css({
          'background': 'url(' + src + ') 50% 50%/cover no-repeat'
        });
      }

      $this.remove();
    });

    return this;
  };
})(jQuery);

이 플러그인을 사용하십시오

jQuery('.cover-image').coverImage();

이미지를 가져 와서 이미지의 래퍼 요소에 배경 이미지로 설정 img하고 문서 에서 태그를 제거합니다 . 마지막으로 당신은 사용할 수 있습니다

순수한 CSS

이를 폴백으로 사용할 수 있습니다. 이미지는 컨테이너를 덮도록 확대되지만 축소되지는 않습니다.

CSS

div {
  height: 8em;
  width: 15em;
  overflow: hidden;
}

div img {
  min-height: 100%;
  min-width: 100%;
  width: auto;
  height: auto;
  max-width: none;
  max-height: none;
  display: block;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

이것이 행복한 코딩을 도울 수 있기를 바랍니다!


답변

CSS3 덕분에

img
{
   object-fit: contain;
}

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

항상 외부인으로서의 IE 및 EDGE :
http://caniuse.com/#feat=object-fit


답변

2019 년 업데이트

이제 object-fit다음 값을 허용하는 css 특성을 사용할 수 있습니다 .fill | contain | cover | none | scale-down

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

예를 들어 이미지가 들어있는 컨테이너가있을 수 있습니다.

<div class="container">
    <img src="" class="container_img" />
</div>

.container {
    height: 50px;
    width: 50%;

.container_img {
    height: 100%;
    width: 100%;
    object-fit: cover;

답변

HTML과 CSS만으로는 불가능하거나 최소한 이국적이고 복잡합니다. 자바 스크립트를 기꺼이 던져 넣으려면 jQuery를 사용하는 솔루션이 있습니다.

$(function() {
    $(window).resize(function() {
        var $i = $('img#image_to_resize');
        var $c = $img.parent();
        var i_ar = $i.width() / $i.height(), c_ar = $c.width() / $c.height();            
        $i.width(i_ar > c_ar ? $c.width() : $c.height() * (i_ar));
    });
    $(window).resize();
});

크기에 관계없이 항상 부모 요소 안에 맞도록 이미지 크기가 조정됩니다. 그리고 $(window).resize()이벤트에 바인딩 되면 사용자가 창 크기를 조정하면 이미지가 조정됩니다.

이것은 컨테이너의 이미지를 중앙에 배치하려고 시도하지는 않지만 가능할 것입니다.