Development Tip

CSS로 배경 이미지 자르기 / 자르기

yourdevel 2020. 11. 11. 20:45
반응형

CSS로 배경 이미지 자르기 / 자르기


이 HTML이 있습니다.

<div id="graphic">lorem ipsum</div>

이 CSS로 :

#graphic { background-image: url(image.jpg); width: 200px; height: 100px;}

적용하는 배경 이미지는 200x100 픽셀이지만 배경 이미지의 잘린 부분 만 200x50 픽셀로 표시하고 싶습니다.

background-clip이에 대한 올바른 CSS 속성이 아닌 것 같습니다. 대신 무엇을 사용할 수 있습니까?

background-position 표시하려는 이미지 부분이 CSS가 정의 된 요소보다 작은 스프라이트 컨텍스트에서 위의 CSS를 사용하고 있기 때문에 사용해서는 안됩니다.


자체 차원 컨텍스트가있는 의사 요소에 그래픽을 넣을 수 있습니다.

#graphic {
  position: relative;
  width: 200px;
  height: 100px;
}
#graphic::before {
  position: absolute;
  content: '';
  z-index: -1;
  width: 200px;
  height: 50px;
  background-image: url(image.jpg);
}

#graphic {
    width: 200px;
    height: 100px;
    position: relative;
}
#graphic::before {
    content: '';
    
    position: absolute;
    width: 200px;
    height: 50px;
    z-index: -1;
    
    background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */
}
<div id="graphic">lorem ipsum</div>

브라우저 지원은 좋지만 IE8을 지원해야하는 경우 단일 콜론을 사용하십시오 :before. IE는 이전 버전에서 두 가지 구문을 모두 지원하지 않습니다.


다음과 같이 작성할 수 있습니다.

#graphic { 
 background-image: url(image.jpg); 
 background-position: 0 -50px; 
 width: 200px; 
 height: 100px;
}

Another option is to use linear-gradient() to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...

.flair {
  min-width: 50px; /* width larger than sprite */
  text-indent: 60px;
  height: 25px;
  display: inline-block;
  background:
    linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,
    url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;
}

.flair-classic {
  background-position: 50px 0, 0 -25px;
}

.flair-r2 {
  background-position: 50px 0, -50px -175px;
}

.flair-smite {
  text-indent: 35px;
  background-position: 25px 0, -50px -25px;
}
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />
<br />
<span class="flair flair-classic">classic sprite</span><br /><br />
<span class="flair flair-r2">r2 sprite</span><br /><br />
<span class="flair flair-smite">smite sprite</span><br /><br />

I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before or ::after elements because I'm already using them for another hack.

참고URL : https://stackoverflow.com/questions/7777159/clip-crop-background-image-with-css

반응형