어떻게 에뮬레이션하도록 배경 크기: 커버를 img&gt

상자 안에 있는 이미지가 어떻게 크기조정할 및 위치변경합니다, 이런 방식으로 전체 https://xxx. '배경 크기 자동화합니다 방식과 유사합니다. 빽이라는 '였다.

<div class="box" style="width: 100px; height: 100px;">
  <img src="pic.jpg" width="413" height="325">
</div>

저도 '요구' 를 추가해야 할 오버플로입니다: hidden '이미지와 확인란 포지셔닝하십시오: 절대 '. 하지만, 이 식을 얻을 수 있는 새로운 나를 what& # 39 의 크기, 왼쪽 오른쪽 이미지용 + 고위직?

질문에 대한 의견 (6)

39 의 뭐하러요 it& 했다. 이 alone with CSS 로 수행할 수 있게 되었습니다.

새로운 CSS 속성을 충족합니다 객체에는 ([현재 브라우저 지원] [2])

그냥 세트 '충족합니다 객체에는: img ',' 를 '빽이라는

39 너회가 don& 잡기 '에'! '하는' img div 못할 정도였습니다.

  • [바이올린] [3] *

<! - begin 스니핏: js 숨기십시오: 참 - &gt.

img {
  width: 100px;
  height: 100px;
}
.object-fit {
  display: block;
  object-fit: cover;
}
.original {
  width: auto;
  height: auto;
  display: block;
}

<p>Img 'squashed' - not good</p>

<p>object-fit: cover -
   The whole image is scaled down or expanded till it fills the box completely, the aspect ratio is maintained. This normally results in only part of the image being visible. </p>

<p>Original ing</p>

끝 - &lt 스니핏 >;!

이 새로운 속성에 대해 더 많이 읽을 수 있어 이 웹판포름 문서.

또한 이 [a 바이올린] [5] 위에서 모든 값을 확인할 수 있는 '문서' 충족합니다 객체에는 재산이잖아

[2]: http://caniuse.com/ # 성과 = 충족합니다 객체에는

해설 (7)

Css 솔루션이므로 img 태그의 크기를 사용하여 배빠르게 빽이라는 순결케 충분히 닫으십시오 배경 매우 높은 브라우저 지원 (IE8+):

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

.container {

  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  overflow: hidden;

}

.container img {

  position: absolute;
  top: 50%;
  left: 50%;

  width: auto;
  height: auto;

  max-height: none;
  max-width: none;

  min-height: 100%;
  min-width: 100%;

  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);

}
<div class="container">

</div>

끝 - &lt 스니핏 >;!

해설 (3)
해결책
  • 이 쉬울 수 있습니다 *

jQuery


$('.box').each(function() {
    //set size
    var th = $(this).height(),//box height
        tw = $(this).width(),//box width
        im = $(this).children('img'),//image
        ih = im.height(),//inital image height
        iw = im.width();//initial image width
    if (ih>iw) {//if portrait
        im.addClass('ww').removeClass('wh');//set width 100%
    } else {//if landscape
        im.addClass('wh').removeClass('ww');//set height 100%
    }
    //set offset
    var nh = im.height(),//new image height
        nw = im.width(),//new image width
        hd = (nh-th)/2,//half dif img/box height
        wd = (nw-tw)/2;//half dif img/box width
    if (nh
해설 (12)

또한 뭐하러요 it& # 39, s worth width&quot &quot 설정하는 대신, 동일한 효과를 통해 제작될 수 있습니다. 및 &quot height"; (이 외곽진입 브트와 그들을 설정뿐입니다 손상될 수):

"'최소 너버: 100%, 최소 높이: 100%, "'

또는

"'최소 너버: 진동현 () 가 원하는 대로 뷰포트가 너버). 최소 높이: () 가 원하는 대로 뷰포트가 높이) vh. "'

함께

"'오버플로입니다: 숨겨짐. "'

상위

)

해설 (1)

이 의견은 추가로 위한 래퍼 (image:

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

<div class="wrap">
  <div class="inner">

  </div>
</div>

끝 - &lt 스니핏 >;!

이러한 CSS 및 사용.

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

.wrap {
  position: relative;
  width: 100%;
  height: 200px;
  background: rgba(255, 0, 0, 0.3);
  overflow: hidden;
}

.inner {
  position: absolute;
  min-width: 100%;
  height: 100%;
  left: 50%;
  -moz-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
}

.inner img {
  position: absolute;
  min-height: 100%;
  min-width: 100%;
  top: 50%;
  left: 50%;
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

끝 - &lt 스니핏 >;!

이는 apc® 예: https://jsfiddle.net/kr60jroe/

해설 (1)

이것은 내 외곽진입:

//collect the nodes
var parent = $('.box');
var img = $('image', box);

//remove width and height attributes
img.removeAttr('width');
img.removeAttr('height');

//set initial width
img.attr('width', parent.width());

//if it's not enough, increase the width according to the height difference
if (img.height() < parent.height()) {
    img.css('width', img.width() * parent.height() / img.height());
}

//position the image in the center
img.css({
    left: parseInt((img.width() - parent.width())/-2) + 'px',
    top: parseInt((img.height() - parent.height())/-2) + 'px'
});

[바이올린] (http://jsfiddle.net/XHtVy/1/)

해설 (1)

충스러웠으니 https://developer.mozilla.org/en-US/docs/Web/CSS/background-size:

cover
    This keyword specifies that the background image should be scaled to be as small as possible while ensuring both its dimensions are greater than or equal to the corresponding dimensions of the background positioning area.

따라서 you& # 39, re 인컨텍스트 보면 '너버 있다. 100% '또는' 높이: '중' 상위 'div 내에 중첩됩니다 100% 가 생성됩니다. 그래서 우리는 다음과 같은 논리가 사용할 수 있습니다.

var makeBackgroundCover = function (div) {
    $(div + " img").css("height", "100%");
    if ($(div + " img").width() < $(div).width()) {
        $(div + " img").css({
            "height": "auto",
            "width": "100%"
        });
    }
}

이 함수는 모두 다음 fs@snapa 수평 및 수직 이미지 작업을 해야했다.

http://jsfiddle.net/2r5Cb/

해설 (4)

39 의 자바스크립트 함수를 here& 깨끗한 이를 구축현 및 오버클로킹된 예:

function backgroundCover(elementSizes, containerSizes) {
    var elementRatio = elementSizes.width / elementSizes.height,
        containerRatio = containerSizes.width / containerSizes.height;
        width = null,
        height = null;
    if (containerRatio > elementRatio) {
        width = Math.ceil( containerSizes.width );
        height = Math.ceil( containerSizes.width / elementRatio );
    } else {
        width = Math.ceil( containerSizes.height * elementRatio );
        height = Math.ceil( containerSizes.height );
    }
    return { width, height };
}

39 의 예를 들어 here& 구축현:

  • HTML *

<div class="photo"></div>
  • CSS *
.photo {
    position: relative;
    overflow: hidden;
    width: 200px;
    padding-bottom: 75%; /* CSS technique to give this element a 4:3 ratio. */
}
.photo img {
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
  • JavaScript *
$( window ).on( 'resize', function() {
    $( '.cover-photo' ).each( function() {
        var img = $( 'img', this ),
            imgWidth = img.attr( 'width' ),
            imgHeight = img.attr( 'height' ),
            containerWidth = $( this ).width(),
            containerHeight = $( this ).height(),
            newSizes = backgroundCover( { width: imgWidth, height: imgHeight }, { width: containerWidth, height: containerHeight } );
        img.css( {
            width: newSizes.width,
            height: newSizes.height
        } );
    } );
} );
해설 (0)

이 날, 우리가 단순히 읽는 동안 파업을 수락됨 오토메이티드 이미지가 # 39, & # 39, portrait& 여부에 대한 테스트 # 39, & # 39, 또는 landscape&.

   if (ih>iw) {//if portrait

39 의 경우, OP, that& 옳다. 그러나 다른 다룰 수 있고, & # 39 의 화면 비율을 사각형과 /dev/raw/raw200 시행하십시오 컨테이너입니다 child& # 39; - 이미지를 고려해:

    var int_container_width  = parseInt( $_container.width()  );
    var int_container_height = parseInt( $_container.height() );
    var num_container_aspect = int_container_width/int_container_height;

    var int_image_width      = parseInt( $_image.width() );
    var int_image_height     = parseInt( $_image.height());
    var num_image_aspect     = int_image_width/int_image_height;

    if ( num_image_aspect > num_container_aspect){
      num_scale = int_container_width/int_image_width * 100;
    } else {
      num_scale = int_container_height/int_image_height * 100;
    }
해설 (2)

이는 css 솔루션이므로 순결케 래퍼 (wrapper) 로 정의할 수 있습니다.

div.cover {
  position: fixed; 
  top: -50%; 
  left: -50%; 
  width: 200%; 
  height: 200%;
}

그리고 img:

img.cover {
  position: absolute; 
  top: 0; 
  left: 0; 
  right: 0; 
  bottom: 0; 
  margin: auto; 
  min-width: 50%;
  min-height: 50%;
  overflow-x: hidden;
}

이 라이브 예:

http://codepen.io/ErwanHesry/pen/JcvCw

해설 (2)

이미지에 대한 태그번호 :&quot 객체에는 빽이라는 충족합니다 &quot 이 스타일을 사용할 수 있습니다;;; 또한 이 링크를 통해 지원할 수 https://css-tricks.com/almanac/properties/o/object-fit/

해설 (0)

I made a 및 배경 포지셔닝하십시오 센터 크기 빽이라는 배경 에뮬레이션하도록 뭔가 할 수도 있다.

그냥 &quot top&quo , 시켜버리므로 변경하십시오 확인표시를 위치를 변경할 수 있습니다. , 충족되었으며 &quot left&quo. img 의

  • CSS *
.box{
    overflow:hidden;
    position:relative;
}

.box img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
}
    • JS
$('.box').each(function() {
     //aspect ratio of container
     var boxRatio = $(this).height() / $(this).width(); 
     //aspect ration of image
     var imageRatio = $(this).children('img').height() / $(this).children('img').width();
     //set width or height 100% depend of difference
     if (imageRatio > boxRatio) {
          $(this).children('img').css({"width":"100%","height":"auto"});                
     } else {
          $(this).children('img').css({"height":"100%","width":"auto" });
     }
});

이 함수는 &quot 활성화할 수 있는 load"; 및 &quot resize"; 이벤트.

해설 (0)

이 질문에 대한 문제가 발생할 수 있는 솔루션을 찾는 것으로 오늘 내가 한 사람이 여러 협력합니다 가로방향입니다, 초상화, 사각형에는, 사각형, 임의의 크기, 나는 내 자신의 코드를 상술합니다 이미지와 컨테이너입니다 포함되어 있습니다.

또한, ll, you& 할 때마다 이를 다시 실행하십시오 응답하여 작동합니까 # 39 그냥 창 크기를 조절합니다.

  • 이스피들 *:

http://jsfiddle.net/66c43ao1/

  • HTML *
<div class="test">
    <div class="cover">

    </div>
</div>
  • CSS *
/* modify the width and height below to demonstrate coverage */
.test {
    height: 300px;
    position: relative;
    width: 500px;
}
/* you will need the below styles */
.cover {
    height: 100%;
    left: 0;
    overflow: hidden;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: 1;
}
    • JS
$('.cover').each(function() {
    var containerHeight = $(this).height(),
        containerWidth  = $(this).width(),
        image           = $(this).children('img'),
        imageHeight     = image.attr('height'),
        imageWidth      = image.attr('width'),
        newHeight       = imageHeight,
        newWidth        = imageWidth;

    if (imageWidth < containerWidth) {
        // if the image isn't wide enough to cover the space, scale the width
        newWidth        = containerWidth;
        newHeight       = imageHeight * newWidth/imageWidth;
    }
    if (imageHeight < containerHeight) {
        // if the image isn't tall enough to cover the space, scale the height
        newHeight       = containerHeight;
        newWidth        = imageWidth * newHeight/imageHeight;
    }

    var marginLeft      = (newWidth - containerWidth)/2;
    var marginTop       = (newHeight - containerHeight)/2;

    image.css({
        marginLeft  : '-' + marginLeft + 'px',
        marginTop   : '-' + marginTop + 'px',
        height      : newHeight,
        width       : newWidth
    });
});

물론 이 같은 일을 할 수 있는 라이브러리를 사용하는 등 좋은 성과를 거둘 수 있을 수 있지만, 내가 찾은 이 솔루션은 박스트리치 제 목적 (증가하지 않고 종속물, 경량화 등).

해설 (0)

이미지 없이, 그냥 상자에 스케쳐내 크기조정 이미지 중심으로 이 코드를 사용하여:

.box {
    width: 100px;
    height: 100px;
    overflow: hidden;
    position: relative;
}
.box img {
    width: 413px;
    height: 325px;
    position: absolute;
    left: 50%;
    top: 50%;
}

맞게 이미지 크기를 조절할 수 있도록 하는 경우, 다음 코드를 사용합니다.

.box {
    width: 100px;
    height: 100px;
}
.box img {
    width: 100%;
    height: auto;
}

이 코드는 나갈 경우 일부 이미지가 보다 더 큰 공백이 있다. 이러한 경우, 그냥 배경 및 사용 설정할 수 있습니다 괜찼습니다 작동합니까 이미지로 '배경 크기: 빽이라는, '.

해설 (2)

내가 만든 함수를 그것을 어떻게해야합니다 아래입니다. 난 뒤 일부 논리를 수락됨 오토메이티드 에서 작동하도록 조정됐다 만들어 모든 컨테이너입니다 제거율 이미지 크기: 다음 그림 있는 데 비해 더 치수이고 컨테이너입니다 원하는거요 치수처리 조정하십시오. # 39, & # 39 는 center& 덧붙였다. 인수 (# 39, & # 39 true&. 센터, 거짓값 세트 迈向 상단형 / 왼쪽).

39 m / Y 를 사용하여, CSS3 i& 트란스라테스 이해했소 apc® 수 있지만, 그것 없이는 쉽게 부족합니다.

39 의 here& 코드:

var coverImage = function(wrap, center) {

  if (typeof center === 'undefined') {
    center = true;
  }

    var wr = $(wrap),
        wrw = wr.width(),
        wrh = wr.height();

  var im = wr.children('img'),
        imw = im.width(),
        imh = im.height();

  var wratio = wrw / imw;
    var hratio = wrh / imh;

  //Set required CSS
  wr.css({'overflow' : 'hidden'});
  im.css({'position' : 'relative'});

  if (wratio > hratio) {
    im.width(wrw);
    im.css({'height' : 'auto'});

    if (center) {
      im.css({
        'top' : '50%',
        'transform' : 'translateY(-50%)'
      });
    }
  } else {
    im.height(wrh);
    im.css({'width' : 'auto'});

    if (center) {
      im.css({
        'left' : '50%',
        'transform' : 'translateX(-50%)'
      });
    }
  }
}

그것을 볼 수 있으며 이스피들 체크아웃합니다 in action: https://jsfiddle.net/cameronolivier/57nLjoyq/2/

해설 (0)