Web Dev/5. Projects

[다락재쉼터] background-image cover와 contain의 차이를 간단하게 짚고 넘어가자

hYhY1234 2021. 4. 7. 16:07
728x90

Background와 관련된 내용은 항상 가물가물한 편인데 아래의 내용은 메모를 해둬야할 것 같아서 정리한다. 

 

stackoverflow.com/questions/9262861/css-background-image-to-fit-width-height-should-auto-scale-in-proportion

 

CSS background image to fit width, height should auto-scale in proportion

I have body { background: url(images/background.svg); } The desired effect is that this background image will have width equal to that of the page, height changing to maintain the proportion....

stackoverflow.com

 

- contain을 사용한 경우

// 한우곰탕
& .first {
  background: url(${(props) => props.menu1}) center rgba(245, 223, 192, 0.7);
  background-repeat: no-repeat;
  background-color: rgba(255, 252, 220, 0.7);
  background-size: contain;
}
// 머리고기
& .second {
  background: url(${(props) => props.menu2}) center rgba(245, 223, 192, 0.7);
  background-repeat: no-repeat;
  background-color: rgba(255, 252, 220, 0.7);
  background-size: contain;
}

background-size: contain의 경우 비율을 유지하면서 이미지를 scaling하는데, 가로나 세로중에 더 큰 부분에 맞추는 것이다. 그림을 보면 더 이해하기 쉽다. 

위의 사진 둘다 background-size: contain으로 해결했다. 

 

 

- cover를 사용하는 경우

// 한우곰탕
& .first {
  background: url(${(props) => props.menu1}) center rgba(245, 223, 192, 0.7);
  background-repeat: no-repeat;
  background-color: rgba(255, 252, 220, 0.7);
  background-size: cover;
}
// 머리고기
& .second {
  background: url(${(props) => props.menu2}) center rgba(245, 223, 192, 0.7);
  background-repeat: no-repeat;
  background-color: rgba(255, 252, 220, 0.7);
  background-size: cover;
}

cover의 경우 비율을 유지하는 것은 contain과 같지만, 전체를 다 덮도록 확대시킨다.

 

 

후기

css를 오랜만에 엄청 다루는데 좀 재밌는것 같다. 공부할 것도 많고. image처리 관련해서는 계속 공부를해서 최적화를 할 수 있도록 해야겠다. 아직 이미지 최적화는쉽지가 않다.