background-size와 같은 것이 있습니까? 이미지 요소에 대해 포함하고 포함합니까?
페이지가 많고 배경 그림이 다른 사이트가 있으며 CSS에서 다음과 같이 표시합니다.
body.page-8 {
background: url("../img/pic.jpg") no-repeat scroll center top #000;
background-size: cover;
}
그러나 <img>
요소를 사용하여 한 페이지에 다른 (전체 화면) 그림을 표시 하고 위의 background-image: cover;
속성 과 동일한 속성을 갖기를 원합니다 (CSS에서 이미지를 표시 할 수 없으며 HTML 문서에서 표시해야 함).
일반적으로 사용합니다 :
div.mydiv img {
width: 100%;
}
또는:
div.mydiv img {
width: auto;
}
사진을 전체적이고 반응 적으로 만듭니다. 그러나 width: 100%
화면이 너무 좁아지면 사진이 너무 많이 줄어들고 ( ) 하단 화면에 신체의 배경색이 표시됩니다. 다른 방법 width: auto;
은 이미지를 전체 크기로만 만들고 화면 크기에 응답하지 않습니다.
이미지를 표시하는 것과 같은 방법으로 이미지를 표시 할 background-size: cover
수 있습니까?
솔루션 # 1- 객체 맞춤 속성 ( IE 부족 지원 )
object-fit: cover;
img에 설정 하십시오.
body {
margin: 0;
}
img {
display: block;
width: 100vw;
height: 100vh;
object-fit: cover;
}
<img src="http://lorempixel.com/1500/1000" />
참조 MDN을 -에 관한 object-fit: cover
:
대체 된 컨텐츠는 요소의 전체 컨텐츠 상자를 채우면서 종횡비를 유지하도록 크기가 조정됩니다. 객체의 종횡비가 상자의 종횡비와 일치하지 않으면 객체가 맞게 잘립니다.
또한 이미지에 적용된 것과 배경 이미지에 적용된 것을 비교하는 이 Codepen 데모 를 참조하십시오object-fit: cover
background-size: cover
해결 방법 # 2-img를 CSS가있는 배경 이미지로 교체
body {
margin: 0;
}
img {
position: fixed;
width: 0;
height: 0;
padding: 50vh 50vw;
background: url(http://lorempixel.com/1500/1000/city/Dummy-Text) no-repeat;
background-size: cover;
}
<img src="http://placehold.it/1500x1000" />
실제로 IE8에서도 작동하는 매우 간단한 CSS 솔루션 이 있습니다.
.container {
position: relative;
overflow: hidden;
/* Width and height can be anything. */
width: 50vw;
height: 50vh;
}
img {
position: absolute;
/* Position the image in the middle of its container. */
top: -9999px;
right: -9999px;
bottom: -9999px;
left: -9999px;
margin: auto;
/* The following values determine the exact image behaviour. */
/* You can simulate background-size: cover/contain/etc.
by changing between min/max/standard width/height values.
These values simulate background-size: cover
*/
min-width: 100%;
min-height: 100%;
}
<div class="container">
<img src="http://placehold.it/200x200" alt="" />
</div>
채우려는 컨테이너 요소를 가질 수 있다고 가정하면 이것이 작동하는 것처럼 보이지만 약간의 해킹을 느낍니다. 본질적으로, 나는 min/max-width/height
더 큰 영역에서 사용하고 그 영역을 원래 크기로 다시 스케일링합니다.
.container {
width: 800px;
height: 300px;
border: 1px solid black;
overflow:hidden;
position:relative;
}
.container.contain img {
position: absolute;
left:-10000%; right: -10000%;
top: -10000%; bottom: -10000%;
margin: auto auto;
max-width: 10%;
max-height: 10%;
-webkit-transform:scale(10);
transform: scale(10);
}
.container.cover img {
position: absolute;
left:-10000%; right: -10000%;
top: -10000%; bottom: -10000%;
margin: auto auto;
min-width: 1000%;
min-height: 1000%;
-webkit-transform:scale(0.1);
transform: scale(0.1);
}
<h1>contain</h1>
<div class="container contain">
<img
src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg"
/>
<!-- 366x200 -->
</div>
<h1>cover</h1>
<div class="container cover">
<img
src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg"
/>
<!-- 366x200 -->
</div>
아니 , 당신은 그것을 꽤 좋아할 수 background-size:cover
없지만 ..
이 접근 방식은 아주 가깝습니다. JavaScript를 사용하여 이미지가 가로인지 세로인지를 결정하고 그에 따라 스타일을 적용합니다.
JS
$('.myImages img').load(function(){
var height = $(this).height();
var width = $(this).width();
console.log('widthandheight:',width,height);
if(width>height){
$(this).addClass('wide-img');
}else{
$(this).addClass('tall-img');
}
});
CSS
.tall-img{
margin-top:-50%;
width:100%;
}
.wide-img{
margin-left:-50%;
height:100%;
}
커버와 포함을 에뮬레이트하는 간단한 솔루션을 찾았습니다. 순수한 CSS이며 동적 크기의 컨테이너에서 작동하며 이미지 비율을 제한하지 않습니다.
IE 또는 16 이전의 Edge를 지원할 필요가 없으면 객체 적합을 사용하는 것이 좋습니다.
배경 크기 : 덮개
.img-container {
position: relative;
overflow: hidden;
}
.background-image {
position: absolute;
min-width: 1000%;
min-height: 1000%;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%) scale(0.1);
z-index: -1;
}
<div class="img-container">
<img class="background-image" src="https://picsum.photos/1024/768/?random">
<p style="padding: 20px; color: white; text-shadow: 0 0 10px black">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
이미지의 자연 크기가 표시되는 크기보다 큰 경우 1000 %가 사용됩니다. 예를 들어 이미지가 500x500이지만 컨테이너가 200x200 인 경우입니다. 이 솔루션을 사용하면 이미지가 최소 너비 / 최소 높이로 인해 2000x2000으로 크기가 조정 된 다음 200x200으로 축소됩니다 (로 인해 transform: scale(0.1)
).
x10 팩터는 x100 또는 x1000으로 대체 될 수 있지만 일반적으로 20x20 div에서 2000x2000 이미지를 렌더링하는 것은 바람직하지 않습니다. :)
배경 크기 : 포함
동일한 원칙에 따라이 규칙을 사용하여 에뮬레이션 할 수도 있습니다 background-size: contain
.
.img-container {
position: relative;
overflow: hidden;
z-index: 0;
}
.background-image {
position: absolute;
max-width: 10%;
max-height: 10%;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%) scale(10);
z-index: -1;
}
<div style="background-color: black">
<div class="img-container">
<img class="background-image" src="https://picsum.photos/1024/768/?random">
<p style="padding: 20px; color: white; text-shadow: 0 0 10px black">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
</div>
에뮬레이션해야 background-size: contain
했지만 object-fit
지원 부족으로 사용할 수 없었습니다 . 내 이미지에는 정의 된 크기의 컨테이너가 있었고 결국 나를 위해 일했습니다.
.image-container {
height: 200px;
width: 200px;
overflow: hidden;
background-color: rebeccapurple;
border: 1px solid yellow;
position: relative;
}
.image {
max-height: 100%;
max-width: 100%;
margin: auto;
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}
<!-- wide -->
<div class="image-container">
<img class="image" src="http://placehold.it/300x100">
</div>
<!-- tall -->
<div class="image-container">
<img class="image" src="http://placehold.it/100x300">
</div>
설정 시도 모두 min-height
와 min-width
함께 display:block
:
img {
display:block;
min-height:100%;
min-width:100%;
}
( 바이올린 )
이미지의 포함 요소가 position:relative
또는 position:absolute
인 경우 이미지가 컨테이너를 덮습니다. 그러나 중앙에 있지 않습니다.
이미지가 가로 (설정 margin-left:-50%
) 또는 세로 (설정 margin-top:-50%
)로 오버플로되는지 여부를 알고 있으면 이미지를 쉽게 가운데에 맞출 수 있습니다 . CSS 미디어 쿼리 (및 일부 수학)를 사용하여이를 파악할 수 있습니다.
할 수있는 일은 'style'속성을 사용하여 요소에 배경 이미지를 추가하는 것입니다.이 방법으로 HTML에서 이미지를 계속 호출하지만 여전히 background-size를 사용할 수 있습니다 : cover css behaviour :
HTML :
<div class="image-div" style="background-image:url(yourimage.jpg)">
</div>
CSS :
.image-div{
background-size: cover;
}
HTML에 동적으로로드해야하는 요소에 background-size : cover 동작을 추가하는 방법입니다. 그런 다음 background-position : center와 같은 멋진 CSS 클래스를 사용할 수 있습니다. 팔
CSS를 사용하면 시뮬레이션 할 수 있습니다 object-fit: [cover|contain];
. 사용 transform
하고 [max|min]-[width|height]
있습니다. 완벽하지 않습니다. 이미지가 컨테이너보다 넓고 짧은 경우에는 효과가 없습니다.
.img-ctr{
background: red;/*visible only in contain mode*/
border: 1px solid black;
height: 300px;
width: 600px;
overflow: hidden;
position: relative;
display: block;
}
.img{
display: block;
/*contain:*/
/*max-height: 100%;
max-width: 100%;*/
/*--*/
/*cover (not work for images wider and shorter than the container):*/
min-height: 100%;
width: 100%;
/*--*/
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<p>Large square:
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x1000"></span>
</p>
<p>Small square:
<span class="img-ctr"><img class="img" src="http://placehold.it/100x100"></span>
</p>
<p>Large landscape:
<span class="img-ctr"><img class="img" src="http://placehold.it/2000x1000"></span>
</p>
<p>Small landscape:
<span class="img-ctr"><img class="img" src="http://placehold.it/200x100"></span>
</p>
<p>Large portrait:
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x2000"></span>
</p>
<p>Small portrait:
<span class="img-ctr"><img class="img" src="http://placehold.it/100x200"></span>
</p>
<p>Ultra thin portrait:
<span class="img-ctr"><img class="img" src="http://placehold.it/200x1000"></span>
</p>
<p>Ultra wide landscape (images wider and shorter than the container):
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x200"></span>
</p>
IE의 경우 두 번째 줄을 포함해야합니다-너비 : 100 %;
.mydiv img {
max-width: 100%;
width: 100%;
}
메신저는 '댓글 추가'를 허용하지 않았지만 Eru Penkman이 한 일은 꽤 많은 자리에 있습니다. 배경 커버와 같이 변경하면됩니다.
.tall-img{
margin-top:-50%;
width:100%;
}
.wide-img{
margin-left:-50%;
height:100%;
}
에
.wide-img{
margin-left:-42%;
height:100%;
}
.tall-img{
margin-top:-42%;
width:100%;
}
나는 이것이 오래되었다는 것을 알고 있지만 위에서 본 많은 솔루션은 이미지 / 비디오가 컨테이너에 비해 너무 커서 실제로 배경 크기의 덮개처럼 작동하지 않는 문제가 있습니다. 그러나 나는 이미지와 비디오에서 작동하도록 "유틸리티 클래스"를 만들기로 결정했다. 컨테이너에 .media-cover-wrapper 클래스를 제공하고 미디어 항목 자체에 .media-cover 클래스를 제공하십시오.
Then you have the following jQuery:
function adjustDimensions(item, minW, minH, maxW, maxH) {
item.css({
minWidth: minW,
minHeight: minH,
maxWidth: maxW,
maxHeight: maxH
});
} // end function adjustDimensions
function mediaCoverBounds() {
var mediaCover = $('.media-cover');
mediaCover.each(function() {
adjustDimensions($(this), '', '', '', '');
var mediaWrapper = $(this).parent();
var mediaWrapperWidth = mediaWrapper.width();
var mediaWrapperHeight = mediaWrapper.height();
var mediaCoverWidth = $(this).width();
var mediaCoverHeight = $(this).height();
var maxCoverWidth;
var maxCoverHeight;
if (mediaCoverWidth > mediaWrapperWidth && mediaCoverHeight > mediaWrapperHeight) {
if (mediaWrapperHeight/mediaWrapperWidth > mediaCoverHeight/mediaCoverWidth) {
maxCoverWidth = '';
maxCoverHeight = '100%';
} else {
maxCoverWidth = '100%';
maxCoverHeight = '';
} // end if
adjustDimensions($(this), '', '', maxCoverWidth, maxCoverHeight);
} else {
adjustDimensions($(this), '100%', '100%', '', '');
} // end if
}); // end mediaCover.each
} // end function mediaCoverBounds
When calling it make sure to take care of page resizing:
mediaCoverBounds();
$(window).on('resize', function(){
mediaCoverBounds();
});
Then the following CSS:
.media-cover-wrapper {
position: relative;
overflow: hidden;
}
.media-cover-wrapper .media-cover {
position: absolute;
z-index: -1;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
Yeah it may require jQuery but it responds quite well and acts exactly like background-size: cover and you can use it on image and/or videos to get that extra SEO value.
We can take ZOOM approach. We can assume that max 30% (or more upto 100%) can be the zooming effect if aspect image height OR width is less than the desired height OR width. We can hide the rest not needed area with overflow: hidden.
.image-container {
width: 200px;
height: 150px;
overflow: hidden;
}
.stage-image-gallery a img {
max-height: 130%;
max-width: 130%;
position: relative;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
This will adjust images with different width OR height.
background:url('/image/url/') right top scroll;
background-size: auto 100%;
min-height:100%;
encountered same exact symptops. above worked for me.
'Programing' 카테고리의 다른 글
Kotlin의 MutableList를 초기화하여 MutableList를 비우려면 어떻게해야합니까? (0) | 2020.05.07 |
---|---|
UI 스레드에서 작업 계속 (0) | 2020.05.07 |
jQuery를 사용하여 패딩 또는 여백 값을 정수로 픽셀 단위로 표시 (0) | 2020.05.07 |
현재 줄에서 파일 끝까지 모든 텍스트를 VIM에서 어떻게 삭제할 수 있습니까? (0) | 2020.05.07 |
Django Model 객체를 변환하여 모든 필드를 그대로 유지하십시오. (0) | 2020.05.07 |