development

이미지를 늘려서 채울 수있는 방법

big-blog 2020. 5. 13. 20:34
반응형

이미지를 늘려서 채울 수있는 방법
이미지의 가로 세로 비율을 유지하면서?


이 이미지를 넘치 <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


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()이벤트에 바인딩 되면 사용자가 창 크기를 조정하면 이미지가 조정됩니다.

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


외부 containerdiv 의 너비와 높이를 설정하십시오 . 그런 다음 img에서 아래 스타일을 사용하십시오.

.container img{
    width:100%;
    height:auto;
    max-height:100%;
}

이것은 img의 가로 세로 비율을 유지하는 데 도움이됩니다


이미지의 가로 세로 비율을 유지하면서 최대 너비 또는 높이를 설정하려면 (너무 크지 않도록) 다음과 같이하십시오.

img{
   object-fit: contain;
   max-height: 70px;
}

나는이 문제를 발견하여 단순한 문제를 찾고있었습니다. 반응 형 디자인의 웹 페이지를 만들고 있는데 페이지에 배치 된 요소의 너비가 화면 너비의 백분율로 설정되어 있습니다. 높이는 vw 값으로 설정됩니다.

PHP와 데이터베이스 백엔드로 게시물을 추가하고 있기 때문에 순수 CSS는 문제가되지 않았습니다. 그러나 jQuery / javascript 솔루션이 약간 까다 롭다는 것을 알았으므로 깔끔한 솔루션을 생각해 냈습니다.

HTML (또는 PHP)

div.imgfill {
  float: left;
  position: relative;
  background-repeat: no-repeat;
  background-position: 50%  50%;
  background-size: cover;
  width: 33.333%;
  height: 18vw;
  border: 1px solid black; /*frame of the image*/
  margin: -1px;
}
<div class="imgfill" style="background-image:url(source/image.jpg);">
  This might be some info
</div>
<div class="imgfill" style="background-image:url(source/image2.jpg);">
  This might be some info
</div>
<div class="imgfill" style="background-image:url(source/image3.jpg);">
  This might be some info
</div>

style = ""을 사용하면 PHP가 내 페이지를 동적으로 업데이트 할 수 있으며 style = ""과 함께 CSS 스타일은 동적 div 태그를 포함하도록 확장 된 이미지로 완성됩니다.


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;

이 방법을 사용하면 div와 이미지의 이미지 변화 비율로 div를 채울 수 있습니다.

jQuery :

$(window).load(function(){
   $('body').find(.fillme).each(function(){
      var fillmeval = $(this).width()/$(this).height();
      var imgval = $this.children('img').width()/$this.children('img').height();
      var imgClass;
      if(imgval > fillmeval){
          imgClass = "stretchy";
      }else{
          imgClass = "stretchx";
      }
      $(this).children('img').addClass(imgClass);
   });
});

HTML :

<div class="fillme">
   <img src="../images/myimg.jpg" />
</div>

CSS :

.fillme{
  overflow:hidden;
}
.fillme img.stretchx{
  height:auto;
  width:100%;
}
.fillme img.stretchy{
  height:100%;
  width:auto;
}

이것은 나를 위해 속임수를했다

div img {
    width: 100%;
    min-height: 500px;
    width: 100vw;
    height: 100vh;
    object-fit: cover;
}

object-fit: cover;부모 div에서 사용할 수 있습니다 .

https://css-tricks.com/almanac/properties/o/object-fit/


이 이미지 를 넘치 거나 왜곡 시키지 않고 가능한 최대 크기까지 늘릴 수 있습니다.

대다...

img {
  object-fit: cover;
  height: -webkit-fill-available;
}

이미지 스타일.


IMG 태그를 사용하면 쉽습니다.

내가 이걸 만들었 어:

<style>
        #pic{
            height: 400px;
            width: 400px;
        }
        #pic img{
            height: 225px;               
            position: relative;
            margin: 0 auto;
        }
</style>

<div id="pic"><img src="images/menu.png"></div>

$(document).ready(function(){
            $('#pic img').attr({ 'style':'height:25%; display:none; left:100px; top:100px;' })
)}

하지만 #pic {background : url (img / menu.png)} Enyone으로 작동시키는 방법을 찾지 못했습니다. 감사


HTML :

<style>
#foo, #bar{
    width: 50px; /* use any width or height */
    height: 50px;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
}
</style>

<div id="foo" style="background-image: url('path/to/image1.png');">
<div id="bar" style="background-image: url('path/to/image2.png');">

JSFiddle

... 그리고 이미지를 설정하거나 변경하려면 (#foo를 예로 사용) :

jQuery :

$("#foo").css("background-image", "url('path/to/image.png')");

자바 스크립트 :

document.getElementById("foo").style.backgroundImage = "url('path/to/image.png')";

Many of the solutions found here have some limitation: some not working in IE ( object-fit) or older browsers, other solutions do not scale up the images (only shrink it), many solution do not support resize of the window and many are not generic, either expect fix resolution or layout(portrait or landscape)

If using javascript and jquery is not a problem I have this solution based on the code of @Tatu Ulmanen. I fixed some issues, and added some code in case the image is loaded dinamically and not available at begining. Basically the idea is to have two different css rules and apply them when required: one when the limitation is the height, so we need to show black bars at the sides, and othe css rule when the limitation is the width, so we need to show black bars at the top/bottom.

function applyResizeCSS(){
    var $i = $('img#imageToResize');
    var $c = $i.parent();
    var i_ar = Oriwidth / Oriheight, c_ar = $c.width() / $c.height();  
    if(i_ar > c_ar){
        $i.css( "width","100%");
        $i.css( "height","auto");          
    }else{
        $i.css( "height","100%");
        $i.css( "width","auto");
    }
}   
var Oriwidth,Oriheight;
$(function() {
    $(window).resize(function() {
        applyResizeCSS();
    });

    $("#slide").load(function(){
        Oriwidth  = this.width,
        Oriheight = this.height; 
        applyResizeCSS();
    }); 

    $(window).resize();
}); 

For an HTML element like:

<img src="images/loading.gif" name="imageToResize" id="imageToResize"/> 

I had similar issue. I resolved it with just CSS.

Basically Object-fit: cover helps you achieve the task of maintaining the aspect ratio while positioning an image inside a div.

But the problem was Object-fit: cover was not working in IE and it was taking 100% width and 100% height and aspect ratio was distorted. In other words image zooming effect wasn't there which I was seeing in chrome.

The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Once it is in the centre, I give to the image,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

This makes the image get the effect of Object-fit:cover.


Here is a demonstration of the above logic.

https://jsfiddle.net/furqan_694/s3xLe1gp/

This logic works in all browsers.

참고URL : https://stackoverflow.com/questions/1891857/how-do-you-stretch-an-image-to-fill-a-div-while-keeping-the-images-aspect-rat

반응형