Posts /

img요소에 background-size: cover 효과를 낼 수 있는 object-fit: cover

Twitter Facebook Google+
26 Dec 2018

img요소에 background-size:cover 효과를 낼 수 있는 object-fit:cover

‘object-fit: cover’ 속성은 IE, EDGE 브라우저에서는 적용되지 않는 CSS 속성입니다. 하지만 글 아래부분에 IE, EDGE 브라우저에도 img요소에 background-size: cover 효과를 낼 수 있는 방법을 적어놓았습니다

object-fit의 속성

object-fit: fill;
object-fit: contain;
object-fit: cover;
object-fit: none;
object-fit: scale-down;

IE, EDGE에서 적용하기


// Detect objectFit support
if('objectFit' in document.documentElement.style === false) {
  
  // assign HTMLCollection with parents of images with objectFit to variable
  var container = document.getElementsByClassName('classname'); // img를 감싸고 있는 div의 class name 을 써주세요.
  
  // Loop through HTMLCollection
  for(var i = 0; i < container.length; i++) {
    
    // Asign image source to variable
    var imageSource = container[i].querySelector('img').src;
    
    // Hide image
    container[i].querySelector('img').style.display = 'none';
    
    // Add background-size: cover
    container[i].style.backgroundSize = 'cover';
    
    // Add background-image: and put image source here
    container[i].style.backgroundImage = 'url(' + imageSource + ')';
    
    // Add background-position: center center
    container[i].style.backgroundPosition = 'center center';
  }
}
else {
  // You don't have to worry
  console.log('No worries, your browser supports objectFit')
}

codepen에서 확인



Twitter Facebook Google+