etc./StackOverFlow

'div' 컨테이너에 맞게 이미지 크기를 자동으로 조정하려면 어떻게 해야 합니까?

청렴결백한 만능 재주꾼 2021. 12. 28. 01:51
반응형

질문자 :001


너비:높이 비율을 유지하면서 더 작은 너비의 div 컨테이너에 맞도록 큰 이미지의 크기를 어떻게 자동 조정합니까?


예: stackoverflow.com - 이미지가 편집기 패널에 삽입되고 이미지가 너무 커서 페이지에 맞지 않으면 이미지 크기가 자동으로 조정됩니다.



이미지 태그에 명시적인 너비나 높이를 적용하지 마십시오. 대신 다음을 제공하십시오.

 max-width:100%; max-height:100%;

또한 height: auto; 너비만 지정하려는 경우.

예: http://jsfiddle.net/xwrvxser/1/

 img { max-width: 100%; max-height: 100%; } .portrait { height: 80px; width: 30px; } .landscape { height: 30px; width: 80px; } .square { height: 75px; width: 75px; }
 Portrait Div <div class="portrait"> <img src="http://i.stack.imgur.com/xkF9Q.jpg"> </div> Landscape Div <div class="landscape"> <img src="http://i.stack.imgur.com/xkF9Q.jpg"> </div> Square Div <div class="square"> <img src="http://i.stack.imgur.com/xkF9Q.jpg"> </div>


Kevin

개체 맞춤

이 작업을 수행하는 또 다른 방법이 있습니다.

 <img style='height: 100%; width: 100%; object-fit: contain'/>

일을 할 것입니다. CSS 3 항목입니다.

바이올린: http://jsfiddle.net/mbHB4/7364/


Shih-Min Lee

현재 JPEG 또는 PNG 파일과 같은 고정 크기 이미지를 사용하여 결정적인 방식으로 이 작업을 올바르게 수행할 수 있는 방법은 없습니다.

이미지의 크기를 비례적으로 조정하려면 높이 또는 너비 중 하나 를 "100%"로 설정해야 하지만 둘 다 설정해서는 안 됩니다. 둘 다 "100%"로 설정하면 이미지가 늘어납니다.

높이 또는 너비를 선택할지 여부는 이미지와 컨테이너 크기에 따라 다릅니다.

  1. 이미지와 컨테이너가 모두 "세로 모양"이거나 모두 "가로 모양"(각각 너비보다 높거나 높이보다 넓음)인 경우 높이 또는 너비 중 어느 것이 "%100"인지는 중요하지 않습니다. .
  2. 이미지가 세로이고 컨테이너가 가로인 경우 이미지에 height="100%"
  3. 이미지가 가로이고 컨테이너가 세로인 경우 이미지에 width="100%"

이미지가 가변 크기 벡터 이미지 형식인 SVG인 경우 컨테이너에 맞게 확장이 자동으로 수행되도록 할 수 있습니다.

<svg> 태그에 다음 속성이 설정되어 있지 않은지 확인하기만 하면 됩니다.

 height width viewbox

대부분의 벡터 드로잉 프로그램은 SVG 파일을 내보낼 때 이러한 속성을 설정하므로 내보낼 때마다 파일을 수동으로 편집하거나 스크립트를 작성해야 합니다.


Neil

다음은 제공된 이미지가 너무 작거나 너무 커서 div에 맞지 않는 경우에도 늘이지 않고 div 내에서 img를 수직 및 수평으로 정렬하는 솔루션입니다.

HTML 콘텐츠:

 <div id="myDiv"> <img alt="Client Logo" title="Client Logo" src="Imagelocation" /> </div>

CSS 콘텐츠:

 #myDiv { height: 104px; width: 140px; } #myDiv img { max-width: 100%; max-height: 100%; margin: auto; display: block; }

jQuery 부분:

 var logoHeight = $('#myDiv img').height(); if (logoHeight < 104) { var margintop = (104 - logoHeight) / 2; $('#myDiv img').css('margin-top', margintop); }

Humble Rumble

간단하게!

컨테이너에 고정 height 를 지정한 다음 그 img 태그에 widthmax-height 합니다.

 <div style="height: 250px"> <img src="..." alt=" " style="width: 100%;max-height: 100%" /> </div>

width max-width 아닌 100%로 설정한다는 것입니다.


Mehdi Maghrouni

이미지를 반응형으로 만드는 방법에는 두 가지가 있습니다.

  1. 이미지가 배경 이미지인 경우.

     #container{ width: 300px; height: 300px; background-image: url(https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg); background-size: cover; background-repeat: no-repeat; background-position: center; } <div id="container"><div>

    여기에서 실행

    그러나 하나를 사용해야 img 가보다 낫다으로 이미지를 넣어 태그를 background-image 당신이에 키워드를 쓸 수있는 검색 엔진 최적화의 관점에서 altimg 태그입니다. 여기에서 이미지를 반응형으로 만들 수 있습니다.

  2. img 태그에 있을 때.

     #container{ max-width: 400px; overflow: hidden; } img{ width: 100%; object-fit: contain; } <div id="container"> <img src="https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg" alt="your_keyword"/> <div>

    여기에서 실행


Siraj Alam

이미지를 div의 배경으로 설정한 다음 CSS background-size 속성 을 사용할 수 있습니다.

 background-size: cover;

"배경 이미지가 배경 이미지로 완전히 덮이도록 배경 이미지를 가능한 한 크게 조정합니다. 배경 이미지의 일부는 배경 위치 지정 영역 내에서 보이지 않을 수 있습니다." -- W3Schools


Chuck Dries

내 솔루션을 확인하십시오: http://codepen.io/petethepig/pen/dvFsA

JavaScript 코드 없이 순수한 CSS로 작성되었습니다. 모든 크기와 방향의 이미지를 처리할 수 있습니다.

주어진 HTML:

 <div class="image"> <div class="trick"></div> <img src="http://placekitten.com/415/200"/> </div>

CSS 코드는 다음과 같습니다.

 .image { font-size: 0; text-align: center; width: 200px; /* Container's dimensions */ height: 150px; } img { display: inline-block; vertical-align: middle; max-height: 100%; max-width: 100%; } .trick { display: inline-block; vertical-align: middle; height: 150px; }

dmitry

이 솔루션은 이미지를 늘리지 않고 전체 컨테이너를 채우지만 이미지의 일부를 자릅니다.

HTML:

 <div><img src="/images/image.png"></div>

CSS:

 div { width: 100%; height: 10em; overflow: hidden; img { min-width: 100%; min-height: 100%; }

Miia Klingstedt

많은 옵션과 함께 필요한 작업을 정확히 수행하는 jQuery 플러그인을 방금 게시했습니다.

https://github.com/GestiXi/image-scale

용법:

HTML

 <div class="image-container"> <img class="scale" data-scale="best-fit-down" data-align="center" src="img/example.jpg"> </div>

자바스크립트

 $(function() { $("img.scale").imageScale(); });

Nicolas BADIA

많은 사람들이 좋은 옵션인 개체 맞춤을 제안한 것을 봅니다. 그러나 이전 브라우저에서도 작동하도록 하려면 쉽게 수행할 수 있는 또 다른 방법이 있습니다.

아주 간단합니다. 내가 취한 접근 방식은 컨테이너 내부에 이미지를 절대 위치로 지정한 다음 조합을 사용하여 중앙에 바로 배치하는 것입니다.

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

일단 중앙에 위치하면 이미지에 부여합니다.

 // For vertical blocks (ie, where height is greater than width) height: 100%; width: auto; // For horizontal blocks (ie, where width is greater than height) height: auto; width: 100%;

이렇게 하면 이미지가 object-fit:cover 의 효과를 얻습니다.


다음은 위의 논리를 보여줍니다.

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

이 논리는 모든 브라우저에서 작동합니다.


Furqan Rahamath

JavaScript가 필요 없는 훨씬 더 나은 솔루션이 있습니다. 완전 반응형이라 많이 사용하고 있습니다. 특정 종횡비가 있는 컨테이너 요소에 모든 종횡비의 이미지를 맞춰야 하는 경우가 많습니다. 그리고 이 모든 것이 완벽하게 반응하는 것은 필수입니다.

 /* For this demo only */ .container { max-width: 300px; margin: 0 auto; } .img-frame { box-shadow: 3px 3px 6px rgba(0, 0, 0, .15); background: #ee0; margin: 20px auto; } /* This is for responsive container with specified aspect ratio */ .aspect-ratio { position: relative; } .aspect-ratio-1-1 { padding-bottom: 100%; } .aspect-ratio-4-3 { padding-bottom: 75%; } .aspect-ratio-16-9 { padding-bottom: 56.25%; } /* This is the key part - position and fit the image to the container */ .fit-img { position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; max-width: 80%; max-height: 90% } .fit-img-bottom { top: auto; } .fit-img-tight { max-width: 100%; max-height: 100% }
 <div class="container"> <div class="aspect-ratio aspect-ratio-1-1 img-frame"> <img src="//placehold.it/400x300" class="fit-img" alt="sample"> </div> <div class="aspect-ratio aspect-ratio-4-3 img-frame"> <img src="//placehold.it/400x300" class="fit-img fit-img-tight" alt="sample"> </div> <div class="aspect-ratio aspect-ratio-16-9 img-frame"> <img src="//placehold.it/400x400" class="fit-img" alt="sample"> </div> <div class="aspect-ratio aspect-ratio-16-9 img-frame"> <img src="//placehold.it/300x400" class="fit-img fit-img-bottom" alt="sample"> </div> </div>

최대 너비와 최대 높이를 독립적으로 설정할 수 있습니다. 이미지는 가장 작은 이미지를 존중합니다(이미지의 값과 종횡비에 따라 다름). 이미지를 원하는 대로 정렬할 수도 있습니다(예: 무한 흰색 배경에 제품 사진의 경우 중앙 하단에 쉽게 배치할 수 있음).


actimel

다음 코드를 사용하여 이 문제를 해결했습니다.

 <div class="container"><img src="image_url" /></div>
 .container { height: 75px; width: 75px; } .container img { object-fit: cover; object-position: top; display: block; height: 100%; width: 100%; }

Serkan KONAKCI

다음은 나를 위해 완벽하게 작동합니다.

 img{ height: 99999px; object-fit:contain; max-height: 100%; max-width: 100%; display: block; margin: auto auto; }

Chong Lip Phang

<style type="text/css"> #container{ text-align: center; width: 100%; height: 200px; /* Set height */ margin: 0px; padding: 0px; background-image: url('../assets/images/img.jpg'); background-size: content; /* Scaling down large image to a div */ background-repeat: no-repeat; background-position: center; } </style> <div id="container> <!-- Inside container --> </div>

easd

여기에 답변된 대로 max-height: 100% vh 단위를 사용할 수도 있습니다. 브라우저(예: Chrome)에서 작동하지 않는 경우:

 img { max-height: 75vh; }

gaborous

다음과 같이 수평 및 수직으로 하이퍼링크 내부의 이미지를 중심에 놓고 비례적으로 크기를 조정했습니다.

 #link { border: 1px solid blue; display: table-cell; height: 100px; vertical-align: middle; width: 100px; } #link img { border: 1px solid red; display: block; margin-left: auto; margin-right: auto; max-height: 60px; max-width: 60px; }

Internet Explorer, Firefox 및 Safari에서 테스트되었습니다.

센터링에 대한 자세한 내용은 여기를 참조하십시오 .


bancer

<img> 태그가 포함된 div에 이미지에 필요한 높이와 너비를 지정합니다. 적절한 스타일 태그에 높이/너비를 지정하는 것을 잊지 마십시오.

<img> 태그에서 max-heightmax-width 를 100%로 지정합니다.

 <div style="height:750px; width:700px;"> <img alt="That Image" style="max-height:100%; max-width:100%;" src=""> </div>

당신이 그것을 올바르게 얻은 후에 적절한 클래스에 세부 사항을 추가할 수 있습니다.


AZD

아래 코드는 이전 답변에서 수정되었으며 storm.jpg 라는 이미지를 사용하여 제가 테스트했습니다.

이것은 이미지를 표시하는 간단한 페이지에 대한 완전한 HTML 코드입니다. 이것은 완벽하게 작동하며 www.resizemybrowser.com에서 테스트했습니다. CSS 코드를 HTML 코드 상단, 헤드 섹션 아래에 배치합니다. 사진을 원하는 곳에 사진 코드를 넣으십시오.

 <html> <head> <style type="text/css"> #myDiv { height: auto; width: auto; } #myDiv img { max-width: 100%; max-height: 100%; margin: auto; display: block; } </style> </head> <body> <div id="myDiv"> <img src="images/storm.jpg"> </div> </body> </html>

dan

브라우저에 배치할 위치의 높이를 알려야 합니다.

 .example { height: 220px; /* DEFINE HEIGHT */ background: url('../img/example.png'); background-size: 100% 100%; background-repeat: no-repeat; }

Rick

편집: Internet Explorer 11에서 이전 테이블 기반 이미지 위치 지정에 문제가 있었습니다( max-height display:table 요소에서 작동하지 않음). Internet Explorer 7과 Internet Explorer 11 모두에서 잘 작동할 뿐만 아니라 더 적은 코드를 필요로 하는 인라인 기반 위치 지정으로 대체했습니다.


다음은 이 주제에 대한 나의 견해입니다. 컨테이너에 지정된 크기가 있는 경우에만 작동하지만( max-widthmax-height 구체적인 크기가 없는 컨테이너와 어울리지 않는 것 같습니다) CSS 콘텐츠를 허용하는 방식으로 작성했습니다. 재사용할 수 있습니다(기존 컨테이너 picture-frame 클래스 및 px125

CSS에서:

 .picture-frame { vertical-align: top; display: inline-block; text-align: center; } .picture-frame.px125 { width: 125px; height: 125px; line-height: 125px; } .picture-frame img { margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */ max-width: 100%; max-height: 100%; display: inline-block; vertical-align: middle; border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */ }

그리고 HTML에서:

 <a href="#" class="picture-frame px125"> <img src="http://i.imgur.com/lesa2wS.png"/> </a>

데모

 /* Main style */ .picture-frame { vertical-align: top; display: inline-block; text-align: center; } .picture-frame.px32 { width: 32px; height: 32px; line-height: 32px; } .picture-frame.px125 { width: 125px; height: 125px; line-height: 125px; } .picture-frame img { margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */ max-width: 100%; max-height: 100%; display: inline-block; vertical-align: middle; border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */ } /* Extras */ .picture-frame { padding: 5px; } .frame { border:1px solid black; }
 <p>32px</p> <a href="#" class="picture-frame px32 frame"> <img src="http://i.imgur.com/lesa2wS.png"/> </a> <a href="#" class="picture-frame px32 frame"> <img src="http://i.imgur.com/kFMJxdZ.png"/> </a> <a href="#" class="picture-frame px32 frame"> <img src="http://i.imgur.com/BDabZj0.png"/> </a> <p>125px</p> <a href="#" class="picture-frame px125 frame"> <img src="http://i.imgur.com/lesa2wS.png"/> </a> <a href="#" class="picture-frame px125 frame"> <img src="http://i.imgur.com/kFMJxdZ.png"/> </a> <a href="#" class="picture-frame px125 frame"> <img src="http://i.imgur.com/BDabZj0.png"/> </a>


편집: JavaScript를 사용하여 추가 개선 가능(이미지 확대):

 function fixImage(img) { var $this = $(img); var parent = $this.closest('.picture-frame'); if ($this.width() == parent.width() || $this.height() == parent.height()) return; if ($this.width() > $this.height()) $this.css('width', parent.width() + 'px'); else $this.css('height', parent.height() + 'px'); } $('.picture-frame img:visible').each(function { if (this.complete) fixImage(this); else this.onload = function(){ fixImage(this) }; });

jahu

이미지<div> 에 맞추는 몇 가지 방법이 있습니다.

 img { object-fit: cover; }

CSS object-fit 속성은 컨테이너에 맞게 <img> 또는 <video> 크기를 조정하는 방법을 지정하는 데 사용됩니다.

이 속성은 콘텐츠에 다양한 방법으로 컨테이너를 채우도록 지시합니다. "그 종횡비 유지" 또는 "최대한 늘리고 많은 공간을 차지하십시오"와 같이.

  • 채우기 - 기본값입니다. 이미지는 주어진 치수를 채우도록 크기가 조정됩니다. 필요한 경우 이미지에 맞게 늘어나거나 찌그러집니다.
  • 포함 - 이미지는 종횡비를 유지하지만 주어진 치수에 맞게 크기가 조정됩니다.
  • 표지 - 이미지가 종횡비를 유지하고 주어진 치수를 채웁니다. 이미지에 맞게 잘립니다.
  • 없음 - 이미지 크기가 조정되지 않습니다.
  • scale-down - 이미지가 none 또는 포함의 가장 작은 버전으로 축소됩니다.

여기 에서 더 많은 작업 샘플을 찾을 수 있습니다.


Sergio Reis

이미지가 너무 작으면 Thorn007에서 허용된 답변이 작동 하지 않습니다.

이를 해결하기 위해 scale factor 를 추가했습니다. 이런 식으로 이미지를 더 크게 만들고 div 컨테이너를 채웁니다.

예시:

 <div style="width:400px; height:200px;"> <img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" /> </div>

노트:

  1. WebKit의 경우 -webkit-transform:scale(4); -webkit-transform-origin:left top; 스타일에서.
  2. 축척 비율이 4이면 최대 너비 = 400/4 = 100 및 최대 높이 = 200/4 = 50이 됩니다.
  3. 다른 솔루션은 최대 너비와 최대 높이를 25%로 설정하는 것입니다. 더 간단합니다.

user217447

저에게 효과가 있는 간단한 솔루션(4단계 수정!!)이 아래에 있습니다. 이 예에서는 너비를 사용하여 전체 크기를 결정하지만 대신 높이를 사용하도록 뒤집을 수도 있습니다.

  1. 이미지 컨테이너에 CSS 스타일 적용(예: <img>)
  2. 너비 속성을 원하는 치수로 설정하십시오.
    • 치수의 경우 % 를 사용하거나 자동 크기 조정(이미지 컨테이너 또는 디스플레이 기준)을 사용합니다.
    • px (또는 기타)를 사용합니다.
  3. 너비에 따라 높이 속성을 자동으로 조정하도록 설정
  4. 즐겨!

예를 들어,

 <img style="width:100%; height:auto;" src="https://googledrive.com/host/0BwDx0R31u6sYY1hPWnZrencxb1k/thanksgiving.png" />

young chisango

간단한 해결책은 Flexbox 를 사용하는 것입니다. 컨테이너의 CSS를 다음과 같이 정의합니다.

 .container{ display: flex; justify-content: center; align-items: center; align-content: center; overflow: hidden; /* Any custom height */ }

포함된 이미지 너비를 100%로 조정하면 크기가 보존된 컨테이너에서 중앙에 좋은 이미지를 얻을 수 있습니다.


Mateo Marin

허용되는 답변을 포함하여 제공된 모든 답변 div 래퍼가 고정된 크기라는 가정 하에 작동합니다. div 래퍼의 크기에 관계없이 수행하는 방법이며 반응형 페이지를 개발하는 경우 매우 유용합니다.

DIV 선택기 내부에 다음 선언을 작성합니다.

 width: 8.33% /* Or whatever percentage you want your div to take */ max-height: anyValueYouWant /* (In px or %) */

IMG 선택기 안에 다음 선언을 넣으십시오.

 width: "100%" /* Obligatory */ max-height: anyValueYouWant /* (In px or %) */

매우 중요:

maxHeight 값은 DIVIMG 선택기 모두에 대해 동일 해야 합니다.


Billal Begueradj

부트스트랩을 사용하는 경우 img 태그에 img-responsive 클래스를 추가하기만 하면 됩니다.

 <img class="img-responsive" src="img_chania.jpg" alt="Chania">

부트스트랩 이미지


HoangYell

약간의 수학으로 해결은 쉽습니다 ...

이미지를 div에 넣은 다음 이미지를 지정하는 HTML 파일에 넣으면 됩니다. 너비와 높이의 정확한 비율을 계산하려면 이미지의 픽셀 값을 사용하여 너비와 높이 값을 백분율로 설정합니다.

예를 들어 너비가 200픽셀이고 높이가 160픽셀인 이미지가 있다고 가정합니다. 너비 값은 더 큰 값이기 때문에 100%라고 안전하게 말할 수 있습니다. 그런 다음 높이 값을 계산하려면 높이를 너비로 나누면 백분율 값이 80%가 됩니다. 코드에서 다음과 같이 보일 것입니다 ...

 <div class="image_holder_div"> <img src="some_pic.png" width="100%" height="80%"> </div>

user2796283

이를 수행하는 가장 간단한 방법은 object-fit .

 <div class="container"> <img src="path/to/image.jpg"> </div> .container{ height: 300px; } .container img{ height: 100%; width: 100%; object-fit: cover; }

부트스트랩을 사용하는 경우 img-responsive 클래스를 추가하고 다음으로 변경합니다.

 .container img{ object-fit: cover; }

Joseph Lariosa

내 대답을 확인하십시오. 이미지를 반응형으로 만들기 - 가장 간단한 방법 -

 img{ width: 100%; max-width: 800px; }

Abhishek Goel

출처 : http:www.stackoverflow.com/questions/3029422/how-do-i-auto-resize-an-image-to-fit-a-div-container

반응형