반응형 웹 디자인 - 이미지
브라우저 창의 크기를 조정하여 페이지에 맞게 이미지 크기가 어떻게 조정되는지 확인합니다.
너비 속성 사용
width
속성이 백분율로 설정되고 속성 height
이 "자동"으로 설정되면 이미지가 반응하고 확대 및 축소됩니다.
예시
img {
width: 100%;
height: auto;
}
위의 예에서 이미지는 원래 크기보다 크게 확대될 수 있습니다. 많은 경우에 더 나은 솔루션은
max-width
속성을 대신 사용하는 것입니다.
max-width 속성 사용
속성이 100%로 설정된 경우 max-width
이미지는 필요한 경우 축소되지만 원래 크기보다 크게 확대되지는 않습니다.
예시
img {
max-width: 100%;
height: auto;
}
예제 웹 페이지에 이미지 추가
예시
img {
width: 100%;
height: auto;
}
배경 이미지
배경 이미지는 크기 조정 및 크기 조정에 응답할 수도 있습니다.
여기에서는 세 가지 다른 방법을 보여줍니다.
1. background-size
속성이 "포함"으로 설정되어 있으면 배경 이미지의 크기가 조정되고 콘텐츠 영역에 맞게 조정됩니다. 그러나 이미지는 종횡비(이미지의 너비와 높이 사이의 비례 관계)를 유지합니다.
다음은 CSS 코드입니다.
예시
div {
width: 100%;
height: 400px;
background-image: url('img_flowers.jpg');
background-repeat: no-repeat;
background-size: contain;
border: 1px solid red;
}
2. background-size
속성이 "100% 100%"로 설정되면 배경 이미지가 전체 콘텐츠 영역을 덮도록 늘어납니다.
다음은 CSS 코드입니다.
예시
div {
width: 100%;
height: 400px;
background-image: url('img_flowers.jpg');
background-size: 100% 100%;
border: 1px solid red;
}
3. background-size
속성이 "cover"로 설정되어 있으면 배경 이미지가 전체 콘텐츠 영역을 덮도록 크기가 조정됩니다. "cover" 값은 종횡비를 유지하고 배경 이미지의 일부가 잘릴 수 있습니다.
다음은 CSS 코드입니다.
예시
div {
width: 100%;
height: 400px;
background-image: url('img_flowers.jpg');
background-size: cover;
border: 1px solid red;
}
다른 장치에 대한 다른 이미지
큰 이미지는 큰 컴퓨터 화면에서는 완벽할 수 있지만 작은 장치에서는 쓸모가 없습니다. 어쨌든 크기를 줄여야 할 때 큰 이미지를 로드하는 이유는 무엇입니까? 부하를 줄이기 위해 또는 다른 이유로 미디어 쿼리를 사용하여 다른 장치에서 다른 이미지를 표시할 수 있습니다.
다음은 다른 장치에 표시될 하나의 큰 이미지와 하나의 작은 이미지입니다.
예시
/* For width smaller than 400px: */
body {
background-image:
url('img_smallflower.jpg');
}
/*
For width 400px and larger: */
@media only screen and (min-width: 400px)
{
body {
background-image: url('img_flowers.jpg');
}
}
브라우저 너비 대신 장치 너비를 확인하는 min-device-width
대신
미디어 쿼리를 사용할 수 있습니다 . min-width
그러면 브라우저 창의 크기를 조정할 때 이미지가 변경되지 않습니다.
예시
/* For devices smaller than 400px: */
body {
background-image:
url('img_smallflower.jpg');
}
/*
For devices 400px and larger: */
@media only screen and (min-device-width: 400px)
{
body {
background-image: url('img_flowers.jpg');
}
}
HTML <그림> 요소
HTML <picture>
요소를 사용하면 웹 개발자가 이미지 리소스를 보다 유연하게 지정할 수 있습니다.
The most common use of the <picture>
element will be for images used in responsive designs. Instead of having one
image that is scaled up or down based on the viewport width, multiple images can
be designed to more nicely fill the browser viewport.
The <picture>
element works similar to the <video>
and
<audio>
elements. You set up different sources, and the first source that fits the
preferences is the one being used:
Example
<picture>
<source srcset="img_smallflower.jpg" media="(max-width:
400px)">
<source srcset="img_flowers.jpg">
<img
src="img_flowers.jpg" alt="Flowers">
</picture>
The srcset
attribute is required, and defines the source of the image.
The media
attribute is optional, and accepts the media queries you find in
CSS @media rule.
You should also define an <img>
element for browsers that do not support the
<picture>
element.