programing

배경 크기와 동일한 것이 있습니까? 이미지 요소에 대한 덮개와 내용물?

easyjava 2023. 9. 26. 22:39
반응형

배경 크기와 동일한 것이 있습니까? 이미지 요소에 대한 덮개와 내용물?

저는 많은 페이지와 다양한 배경 사진이 있는 사이트를 가지고 있으며 CSS에서 다음과 같이 표시합니다.

body.page-8 {
    background: url("../img/pic.jpg") no-repeat scroll center top #000;
    background-size: cover;
}

() 을 하여 한 화면).<img>이 위의다들과 background-image: cover;property (이미지는 CSS에서 표시할 수 없으며 HTML 문서에서 표시해야 함).

일반적으로 사용하는 항목:

div.mydiv img {
    width: 100%;
}

또는:

div.mydiv img {
    width: auto;
}

사진을 풍부하고 반응적으로 만들기 위해서입니다.다()width: 100% 화면이 너무 좁아지면 하단 화면에 신체 배경색이 표시됩니다. 방법인은은width: auto;는 뿐 크기인에는 .

와 같은 ?background-size: cover그런가요?

솔루션 #1 - 객체 맞춤 속성(Laks IE 지원)

설정만 하면 됩니다.object-fit: cover;

body {
  margin: 0;
}
img {
  display: block;
  width: 100vw;
  height: 100vh;
  object-fit: cover; /* or object-fit: contain; */
}
<img src="https://loremflickr.com/1500/1000" alt="A random image from Flickr" />

MDN 참조 - 관련object-fit: cover:

교체된 내용은 요소의 전체 내용 상자를 채우면서 가로 세로 비율을 유지하도록 크기가 조정됩니다.개체의 가로 세로 비율이 상자의 가로 세로 비율과 일치하지 않으면 개체가 적합하도록 잘립니다.

도.object-fit: contain:

교체된 컨텐츠는 요소의 컨텐츠 상자에 맞추면서 가로 세로 비율을 유지하도록 크기가 조정됩니다.개체 전체가 가로 세로 비율을 유지하면서 상자를 채우도록 만들어지므로 개체의 가로 세로 비율이 상자의 세로 비율과 일치하지 않으면 "편지 상자"가 됩니다.

또한 다음을 비교하는 코드펜 데모를 참조하십시오.object-fit: cover으로 이미지에 됩니다.background-size: cover


솔루션 #2 - img를 배경 이미지로 CSS로 대체

body {
  margin: 0;
}

img {
  position: fixed;
  width: 0;
  height: 0;
  padding: 50vh 50vw;
  background: url("https://loremflickr.com/1500/1000") no-repeat;
  background-size: cover;
}
<img src="https://via.placeholder.com/1500x1000" alt="A random image from Flickr" />

채우기를 원하는 컨테이너 요소를 배치할 수 있다고 가정하면, 이는 작동하는 것처럼 보이지만 약간 어색한 느낌이 듭니다., 저는으로,합니다.min/max-width/height더 넓은 영역에서 그 영역을 원래의 차원으로 다시 확장합니다.

.container {
  width: 800px;
  height: 300px;
  border: 1px solid black;
  overflow:hidden;
  position:relative;
}
.container.contain img {
  position: absolute;
  left:-10000%; right: -10000%; 
  top: -10000%; bottom: -10000%;
  margin: auto auto;
  max-width: 10%;
  max-height: 10%;
  -webkit-transform:scale(10);
  transform: scale(10);
}
.container.cover img {
  position: absolute;
  left:-10000%; right: -10000%; 
  top: -10000%; bottom: -10000%;
  margin: auto auto;
  min-width: 1000%;
  min-height: 1000%;
  -webkit-transform:scale(0.1);
  transform: scale(0.1);
}
<h1>contain</h1>
  <div class="container contain">
    <img 
       src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" 
       />
    <!-- 366x200 -->
  </div>
  <h1>cover</h1>
  <div class="container cover">
    <img 
       src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" 
       />
    <!-- 366x200 -->
  </div>

실제로 IE8에서도 작동하는 꽤 간단한 CSS 솔루션이 있습니다.

.container {
  position: relative;
  overflow: hidden;
  /* Width and height can be anything. */
  width: 50vw;
  height: 50vh;
}

img {
  position: absolute;
  /* Position the image in the middle of its container. */
  top: -9999px;
  right: -9999px;
  bottom: -9999px;
  left: -9999px;
  margin: auto;
  /* The following values determine the exact image behaviour. */
  /* You can simulate background-size: cover/contain/etc.
     by changing between min/max/standard width/height values.
     These values simulate background-size: cover
  */
  min-width: 100%;
  min-height: 100%;
}
<div class="container">
    <img src="http://placehold.it/200x200" alt="" />
</div>

저는 cover와 contain 모두를 에뮬레이트할 수 있는 간단한 솔루션을 찾았는데, 이것은 순수한 CSS이며 동적인 차원을 가진 컨테이너에 적합하며, 이미지 비율에 대한 제약도 없습니다.

IE나 16 이전의 Edge를 지원할 필요가 없다면 개체 적합을 사용하는 것이 좋습니다.

배경 사이즈: 커버

.img-container {
  position: relative;
  overflow: hidden;
}

.background-image {
  position: absolute;
  min-width: 1000%;
  min-height: 1000%;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%) scale(0.1);
  z-index: -1;
}
<div class="img-container">
  <img class="background-image" src="https://picsum.photos/1024/768/?random">
  <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
</div>

여기서는 이미지 자연 사이즈가 표시되는 사이즈보다 큰 경우에 1000%를 사용합니다.예를 들어 이미지가 500x500인데 컨테이너가 200x200에 불과한 경우입니다.이 (최소 높이로 가 2000x2000비해)음 해)transform: scale(0.1)).

x10 factor는 x100 또는 x1000으로 대체할 수 있지만, 일반적으로 2000x2000 이미지를 20x20 div로 렌더링하는 것은 이상적이지 않습니다.

배경 크기: 포함

를 데 .background-size: contain:

.img-container {
  position: relative;
  overflow: hidden;
  z-index: 0;
}

.background-image {
  position: absolute;
  max-width: 10%;
  max-height: 10%;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%) scale(10);
  z-index: -1;
}
<div style="background-color: black">
  <div class="img-container">
    <img class="background-image" src="https://picsum.photos/1024/768/?random">
    <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
  </div>
</div>

아니요, 당신은 그것을 마치 당신처럼 얻을 수 없습니다.background-size:cover 하지만..

이 접근법은 자바스크립트를 사용하여 이미지가 가로인지 세로인지를 판단하고 그에 따라 스타일을 적용합니다.

JS

 $('.myImages img').load(function(){
        var height = $(this).height();
        var width = $(this).width();
        console.log('widthandheight:',width,height);
        if(width>height){
            $(this).addClass('wide-img');
        }else{
            $(this).addClass('tall-img');
        }
    });

CSS

.tall-img{
    margin-top:-50%;
    width:100%;
}
.wide-img{
    margin-left:-50%;
    height:100%;
}

http://jsfiddle.net/b3PbT/

당신이 할 수 있는 일은 'style' 속성을 사용하여 요소에 배경 이미지를 추가하는 것입니다. 이렇게 하면 HTML에서 이미지를 호출할 수 있지만 배경 크기: cover css 동작을 사용할 수 있습니다.

HTML:

    <div class="image-div" style="background-image:url(yourimage.jpg)">
    </div>

CSS:

    .image-div{
    background-size: cover;
    }

이렇게 배경 크기를 추가합니다. HTML에 동적으로 로드해야 하는 요소에 커버 동작입니다. 그런 다음 배경 위치: center. boom과 같은 멋진 CSS 클래스를 사용할 수 있습니다.

나는 본받을 필요가 있었습니다.background-size: contain, 사용할 수 없었습니다.object-fit지지가 부족하여 제 이미지에는 치수가 정의된 컨테이너가 있었고 결국 제게 적합하게 되었습니다사용할 수 .

.image-container {
  height: 200px;
  width: 200px;
  overflow: hidden;
  background-color: rebeccapurple;
  border: 1px solid yellow;
  position: relative;
}

.image {
  max-height: 100%;
  max-width: 100%;
  margin: auto;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}
<!-- wide -->
<div class="image-container">
  <img class="image" src="http://placehold.it/300x100">
</div>

<!-- tall -->
<div class="image-container">
  <img class="image" src="http://placehold.it/100x300">
</div>

하면 CSS를 할 수 .object-fit: [cover|contain];있어요. 가.transform그리고.[max|min]-[width|height]. 완벽하지 않습니다.이미지가 컨테이너보다 더 넓고 짧을 경우에는 작동하지 않습니다.

.img-ctr{
  background: red;/*visible only in contain mode*/
  border: 1px solid black;
  height: 300px;
  width: 600px;
  overflow: hidden;
  position: relative;
  display: block;
}
.img{
  display: block;

  /*contain:*/
  /*max-height: 100%;
  max-width: 100%;*/
  /*--*/

  /*cover (not work for images wider and shorter than the container):*/
  min-height: 100%;
  width: 100%;
  /*--*/

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<p>Large square:
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x1000"></span>
</p>
<p>Small square:
<span class="img-ctr"><img class="img" src="http://placehold.it/100x100"></span>
</p>
<p>Large landscape:
<span class="img-ctr"><img class="img" src="http://placehold.it/2000x1000"></span>
</p>
<p>Small landscape:
<span class="img-ctr"><img class="img" src="http://placehold.it/200x100"></span>
</p>
<p>Large portrait:
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x2000"></span>
</p>
<p>Small portrait:
<span class="img-ctr"><img class="img" src="http://placehold.it/100x200"></span>
</p>
<p>Ultra thin portrait:
<span class="img-ctr"><img class="img" src="http://placehold.it/200x1000"></span>
</p>
<p>Ultra wide landscape (images wider and shorter than the container):
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x200"></span>
</p>

줌(ZOOM)으로 접근할 수 있습니다.측면 영상 높이 또는 너비가 원하는 높이 또는 너비보다 작을 경우 최대 30%(또는 최대 100%)가 줌 효과가 될 수 있다고 가정할 수 있습니다.필요하지 않은 나머지 부분은 오버플로우로 숨길 수 있습니다.

.image-container {
  width: 200px;
  height: 150px;
  overflow: hidden;
}
.stage-image-gallery a img {
  max-height: 130%;
  max-width: 130%;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

이렇게 하면 너비나 높이가 다른 이미지가 조정됩니다.

다 설정해 보십시오. min-height그리고.min-width,와 함께display:block:

img {
    display:block;
    min-height:100%;
    min-width:100%;
}

( fid)

과 같은 position:relative아니면position:absolute를 입니다.그러나 중앙에 배치되지는 않습니다.

(set))를 있으면 잡을 수 .margin-left:-50%) 또는 수직(set)margin-top:-50%CSS 미디어 쿼리(및 일부 수학)를 사용하여 이를 파악하는 것이 가능할 수 있습니다.

댓글을 추가하는 것은 허용되지 않습니다. 그래서 이렇게 하지만 예, 에루 펭크만이 한 일은 거의 완벽합니다. 배경 커버처럼 받기 위해서는 변경만 하면 됩니다.

.tall-img{
    margin-top:-50%;
    width:100%;
}
.wide-img{
    margin-left:-50%;
    height:100%;
}

로.

.wide-img{
    margin-left:-42%;
    height:100%;
}
.tall-img{
    margin-top:-42%;
    width:100%;
}

이것이 오래된 것은 알지만 위에서 본 많은 솔루션들은 이미지/비디오가 컨테이너에 비해 너무 커서 실제 배경 크기 커버처럼 작동하지 않는 문제가 있습니다.하지만, 저는 이미지와 비디오에 적합하도록 "유틸리티 수업"을 만들기로 결정했습니다.컨테이너에 클래스 .media-cover-wrapper와 미디어 항목 자체를 클래스 .media-cover로 지정하면 됩니다.

그러면 다음과 같은 jQuery가 있습니다.

function adjustDimensions(item, minW, minH, maxW, maxH) {
  item.css({
  minWidth: minW,
  minHeight: minH,
  maxWidth: maxW,
  maxHeight: maxH
  });
} // end function adjustDimensions

function mediaCoverBounds() {
  var mediaCover = $('.media-cover');

  mediaCover.each(function() {
   adjustDimensions($(this), '', '', '', '');
   var mediaWrapper = $(this).parent();
   var mediaWrapperWidth = mediaWrapper.width();
   var mediaWrapperHeight = mediaWrapper.height();
   var mediaCoverWidth = $(this).width();
   var mediaCoverHeight = $(this).height();
   var maxCoverWidth;
   var maxCoverHeight;

   if (mediaCoverWidth > mediaWrapperWidth && mediaCoverHeight > mediaWrapperHeight) {

     if (mediaWrapperHeight/mediaWrapperWidth > mediaCoverHeight/mediaCoverWidth) {
       maxCoverWidth = '';
       maxCoverHeight = '100%';
     } else {
       maxCoverWidth = '100%';
       maxCoverHeight = '';
     } // end if

     adjustDimensions($(this), '', '', maxCoverWidth, maxCoverHeight);
   } else {
     adjustDimensions($(this), '100%', '100%', '', '');
   } // end if
 }); // end mediaCover.each
} // end function mediaCoverBounds

호출할 때는 페이지 크기 조정을 반드시 처리해야 합니다.

mediaCoverBounds();

$(window).on('resize', function(){
  mediaCoverBounds();
});

그러면 다음 CSS:

.media-cover-wrapper {
  position: relative;
  overflow: hidden;
}

.media-cover-wrapper .media-cover {
  position: absolute;
  z-index: -1;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

예, jQuery가 필요할 수도 있지만 반응이 매우 좋으며 배경 크기와 동일하게 작동합니다. 커버를 씌우고 이미지 및/또는 비디오에 사용하여 추가 SEO 값을 얻을 수 있습니다.

IE6의 경우 두 번째 선 너비(100%)도 포함해야 합니다.

.mydiv img {
    max-width: 100%;
    width: 100%;
}
 
background:url('/image/url/') right top scroll; 
background-size: auto 100%; 
min-height:100%;

위와 같은 증상을 겪었습니다. 저는 효과가 있었습니다.

언급URL : https://stackoverflow.com/questions/11670874/is-there-an-equivalent-to-background-size-cover-and-contain-for-image-elements

반응형