programing

background-size: 표지 background-size: 표지 background-size: 표지 또는또는또는

bestprogram 2023. 8. 15. 11:17

background-size: 표지

의기을시션하어해합니까야떻게면의 을 어떻게 할 수 ?background-size:coverHTML과 에서 사용할 수 .<video>또는<img>?

다음과 같이 작동했으면 합니다.

background-size: cover;
background-position: center center;

이것은 제가 잠시 머리를 빗어넘긴 것이지만, 저는 어떤 스크립트도 사용하지 않는 훌륭한 솔루션을 발견했고, 5줄의 CSS로 비디오에서 완벽한 커버 시뮬레이션을 달성할 수 있습니다(셀렉터와 브래킷을 세는 경우 9개).이것은 CSS3 호환성이 부족한 완벽하게 작동하지 않는 0개의 에지 케이스를 가지고 있습니다.

여기서 예제를 볼 수 있습니다(보관됨).

Timothy 솔루션의 문제는 스케일링을 제대로 처리하지 못한다는 것입니다.주변 요소가 비디오 파일보다 작으면 축소되지 않습니다.비디오 태그에 16px x 9px와 같은 작은 초기 크기를 주어도,auto기본 파일 크기의 최소 크기로 강제 적용됩니다.이 페이지에서 현재 가장 많이 투표된 솔루션으로는 비디오 파일의 크기를 줄이는 것이 불가능하여 급격한 줌 효과가 발생했습니다.

그러나 비디오의 가로 세로 비율이 16:9와 같이 알려진 경우 다음을 수행할 수 있습니다.

.parent-element-to-video {
    overflow: hidden;
}
video {
    height: 100%;
    width: 177.77777778vh; /* 100 * 16 / 9 */
    min-width: 100%;
    min-height: 56.25vw; /* 100 * 9 / 16 */
}

예:position: fixed; width: 100%; height: 100vh;), 그러면 비디오도 그럴 것입니다.

비디오도 중심에 맞추려면 확실한 중심 설정 방법을 사용할 수 있습니다.

/* merge with above css */
.parent-element-to-video {
    position: relative; /* or absolute or fixed */
}
video {
    position: absolute;
    left: 50%; /* % of surrounding element */
    top: 50%;
    transform: translate(-50%, -50%); /* % of current element */
}

물이야론.vw,vh,그리고.transformCSS3이므로 훨씬 이전 브라우저와의 호환성이 필요하다면 스크립트를 사용해야 합니다.

일부 브라우저에서 사용할 수 있습니다.

object-fit: cover;

http://caniuse.com/object-fit

jsFiddle

배경 커버를 사용하는 것은 이미지에 문제가 없으며 너비도 100%입니다.이는 다음과 같은 경우에 최적이 아닙니다.<video>그리고 이 대답들은 너무 복잡합니다.전체 너비 비디오 배경을 만들기 위해 jQuery 또는 JavaScript가 필요하지 않습니다.

내 코드는 커버 윌과 같은 비디오로 배경을 완전히 다루지는 않지만, 대신 가로 세로 비율을 유지하면서 전체 배경을 커버하는 데 필요한 만큼의 크기로 비디오를 만들 것입니다.과도한 비디오는 페이지 가장자리에서 블리딩됩니다. 페이지 가장자리는 비디오를 고정하는 위치에 따라 달라집니다.

답은 매우 간단합니다.

이 HTML5 비디오 코드나 다음과 같은 것을 사용하면 됩니다. (전체 페이지에서 테스트)

html, body {
  width: 100%; 
  height:100%; 
  overflow:hidden;
}

#vid{
  position: absolute;
  top: 50%; 
  left: 50%;
  -webkit-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
  min-width: 100%; 
  min-height: 100%; 
  width: auto; 
  height: auto;
  z-index: -1000; 
  overflow: hidden;
}
<video id="vid" video autobuffer autoplay>
  <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
</video>

최소 높이와 최소 너비를 사용하면 비디오가 일반 해상도에서 일반 브라우저의 가로 세로 비율인 비디오 가로 세로 비율을 유지할 수 있습니다.과도한 비디오는 페이지 측면에서 블리딩됩니다.

제가 이렇게 했습니다.jsFiddle에는 실제 예제가 있습니다.

var min_w = 300; // minimum video width allowed
var vid_w_orig;  // original video dimensions
var vid_h_orig;

jQuery(function() { // runs after DOM has loaded

  vid_w_orig = parseInt(jQuery('video').attr('width'));
  vid_h_orig = parseInt(jQuery('video').attr('height'));
  $('#debug').append("<p>DOM loaded</p>");

  jQuery(window).resize(function () { resizeToCover(); });
  jQuery(window).trigger('resize');
});

function resizeToCover() {
  // set the video viewport to the window size
  jQuery('#video-viewport').width(jQuery(window).width());
  jQuery('#video-viewport').height(jQuery(window).height());

  // use largest scale factor of horizontal/vertical
  var scale_h = jQuery(window).width() / vid_w_orig;
  var scale_v = jQuery(window).height() / vid_h_orig;
  var scale = scale_h > scale_v ? scale_h : scale_v;

  // don't allow scaled width < minimum video width
  if (scale * vid_w_orig < min_w) {scale = min_w / vid_w_orig;};

  // now scale the video
  jQuery('video').width(scale * vid_w_orig);
  jQuery('video').height(scale * vid_h_orig);
  // and center it by scrolling the video viewport
  jQuery('#video-viewport').scrollLeft((jQuery('video').width() - jQuery(window).width()) / 2);
  jQuery('#video-viewport').scrollTop((jQuery('video').height() - jQuery(window).height()) / 2);

  // debug output
  jQuery('#debug').html("<p>win_w: " + jQuery(window).width() + "</p>");
  jQuery('#debug').append("<p>win_h: " + jQuery(window).height() + "</p>");
  jQuery('#debug').append("<p>viewport_w: " + jQuery('#video-viewport').width() + "</p>");
  jQuery('#debug').append("<p>viewport_h: " + jQuery('#video-viewport').height() + "</p>");
  jQuery('#debug').append("<p>video_w: " + jQuery('video').width() + "</p>");
  jQuery('#debug').append("<p>video_h: " + jQuery('video').height() + "</p>");
  jQuery('#debug').append("<p>vid_w_orig: " + vid_w_orig + "</p>");
  jQuery('#debug').append("<p>vid_h_orig: " + vid_h_orig + "</p>");
  jQuery('#debug').append("<p>scale: " + scale + "</p>");
};
#video-viewport {
  position: absolute;
  top: 0;
  overflow: hidden;
  z-index: -1; /* for accessing the video by click */
}

#debug {
  position: absolute;
  top: 0;
  z-index: 100;
  color: #fff;
  font-size: 12pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="video-viewport">
  <video autoplay controls preload width="640" height="360">
    <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"type="video/mp4" />
    <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"type="video/webm" />
    <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"type="video/webm" />
  </video>
</div>

<div id="debug"></div>

Daniel de Wit의 답변과 댓글을 바탕으로 조금 더 검색해보았습니다.해결해 준 그에게 감사합니다.

은 해책은다같습다니과를 사용하는 입니다.object-fit: cover;모든 최신 브라우저가 지원합니다.IE를 지원하려면 객체 맞춤 이미지 또는 객체 맞춤과 같은 폴리필을 사용할 수 있습니다.

데모:

img {
  float: left;
  width: 100px;
  height: 80px;
  border: 1px solid black;
  margin-right: 1em;
}
.fill {
  object-fit: fill;
}
.contain {
  object-fit: contain;
}
.cover {
  object-fit: cover;
}
.none {
  object-fit: none;
}
.scale-down {
  object-fit: scale-down;
}
<img class="fill" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
<img class="contain" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
<img class="cover" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
<img class="none" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
<img class="scale-down" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>

그리고 부모님과 함께:

div {
  float: left;
  width: 100px;
  height: 80px;
  border: 1px solid black;
  margin-right: 1em;
}
img {
  width: 100%;
  height: 100%;
}
.fill {
  object-fit: fill;
}
.contain {
  object-fit: contain;
}
.cover {
  object-fit: cover;
}
.none {
  object-fit: none;
}
.scale-down {
  object-fit: scale-down;
}
<div>
<img class="fill" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
</div><div>
<img class="contain" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
</div><div>
<img class="cover" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
</div><div>
<img class="none" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
</div><div>
<img class="scale-down" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
</div>

다른 답변은 좋았지만 Javascript를 포함하거나 비디오를 수평 및 수직으로 중앙에 배치하지 않습니다.

이 전체 CSS 솔루션을 사용하여 배경 크기를 시뮬레이션하는 비디오를 만들 수 있습니다: cover property:

  video {
    position: fixed;           // Make it full screen (fixed)
    right: 0;
    bottom: 0;
    z-index: -1;               // Put on background

    min-width: 100%;           // Expand video
    min-height: 100%;
    width: auto;               // Keep aspect ratio
    height: auto;

    top: 50%;                  // Vertical center offset
    left: 50%;                 // Horizontal center offset

    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);         // Cover effect: compensate the offset

    background: url(bkg.jpg) no-repeat;      // Background placeholder, not always needed
    background-size: cover;
  }

M-Pixel의 솔루션 Timothy의 답변의 스케일링 문제를 해결한다는 점에서 훌륭합니다(비디오는 스케일업되지만 다운되지는 않으므로 비디오가 정말 크면 일부만 확대된 것을 볼 수 있는 좋은 기회입니다).그러나 이 솔루션은 비디오 컨테이너의 크기와 관련된 잘못된 가정, 즉 뷰포트 너비와 높이의 100%를 기반으로 합니다.저는 그것이 저에게 효과가 없는 몇 가지 사례를 발견했습니다. 그래서 저는 스스로 문제를 해결하기로 결정했고, 궁극적인 해결책을 생각해냈다고 생각합니다.

HTML

<div class="parent-container">
    <div class="video-container">
        <video width="1920" height="1080" preload="auto" autoplay loop>
            <source src="video.mp4" type="video/mp4">
        </video>
    </div>
</div>

CSS

.parent-container {
  /* any width or height */
  position: relative;
  overflow: hidden;
}
.video-container {
  width: 100%;
  min-height: 100%;
  position: absolute;
  left: 0px;
  /* center vertically */
  top: 50%;
  -moz-transform: translate(0%, -50%);
  -ms-transform: translate(0%, -50%);
  -webkit-transform: translate(0%, -50%);
  transform: translate(0%, -50%);
}
.video-container::before {
  content: "";
  display: block;
  height: 0px;
  padding-bottom: 56.25%; /* 100% * 9 / 16 */
}
.video-container video {
  width: auto;
  height: 100%;
  position: absolute;
  top: 0px;
  /* center horizontally */
  left: 50%;
  -moz-transform: translate(-50%, 0%);
  -ms-transform: translate(-50%, 0%);
  -webkit-transform: translate(-50%, 0%);
  transform: translate(-50%, 0%);
}

또한 비디오의 비율을 기준으로 하므로 비디오의 비율이 16/9이 아닌 경우 패딩-하단(%)을 변경할 수 있습니다.그 외에는, 즉시 사용할 수 있습니다.IE9+, Safari 9.0.1, Chrome 46 및 Firefox 41에서 테스트되었습니다.

EDIT (2016년 3월 17일)

이 답변을 게시한 이후로 저는 두 가지를 시뮬레이션하기 위해 작은 CSS 모듈을 작성했습니다.background-size: cover그리고.background-size: contain<video>요소: http://codepen.io/benface/pen/NNdBMj

한 정렬을 합니다.background-position 하십시오. 또한 참고할 사항은contain구현이 완벽하지 않습니다.와는과 다르게 .background-size: contain용기의 너비와 높이가 더 크면 실제 크기를 초과하여 동영상을 확대할 수는 없지만, 그래도 유용할 수 있다고 생각합니다.▁special다▁added니▁i도 추가했습니다.fill-width그리고.fill-height 수있클스래는할과 함께 할 수 contain특별한 혼합물을 얻다contain그리고.cover그것을 사용해보고, 자유롭게 그것을 개선하세요!

object-fit: cover이 IE, Safari 폴리필에 대한 최고의 답변입니다.

https://github.com/constancecchen/object-fit-polyfill

은 그은지니다합원것을 .img,video그리고.picture요소들.

CSS와 little j는 비디오가 배경과 수평 중심을 덮도록 할 수 있습니다.

CSS:

video#bgvid {
    position: absolute;
    bottom: 0px; 
    left: 50%; 
    min-width: 100%; 
    min-height: 100%; 
    width: auto; 
    height: auto; 
    z-index: -1; 
    overflow: hidden;
}

JS: (창 크기 조정으로 바인딩하고 별도로 한 번 호출)

$('#bgvid').css({
    marginLeft : '-' + ($('#bgvid').width()/2) + 'px'
})

긴 댓글 섹션 직후에 JQuery를 기반으로 하는 다음과 같은 기능을 찾으실 수 있을 것입니다.

HTML:

<img width="100%" id="img" src="http://uploads8.wikipaintings.org/images/william-adolphe-bouguereau/self-portrait-presented-to-m-sage-1886.jpg">

JS:

<script type="text/javascript">
window.onload = function(){
       var img = document.getElementById('img')
       if(img.clientHeight<$(window).height()){
            img.style.height=$(window).height()+"px";
       }
       if(img.clientWidth<$(window).width()){
            img.style.width=$(window).width()+"px";
       } 
}
​</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

CSS:

body{
    overflow: hidden;
}

위의 코드는 브라우저 너비와 높이를 사용하는 것입니다. 만약 당신이 div 안에서 이것을 한다면, 당신은 그것을 다음과 같은 것으로 변경해야 할 것입니다.

디브의 경우:

HTML:

<div style="width:100px; max-height: 100px;" id="div">
     <img width="100%" id="img" src="http://uploads8.wikipaintings.org/images/william-adolphe-bouguereau/self-portrait-presented-to-m-sage-1886.jpg">
</div>

JS:

<script type="text/javascript">
window.onload = function(){
       var img = document.getElementById('img')
       if(img.clientHeight<$('#div').height()){
            img.style.height=$('#div').height()+"px";
       }
       if(img.clientWidth<$('#div').width()){
            img.style.width=$('#div').width()+"px";
       } 
}
​</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

CSS:

div{
   overflow: hidden;
}

구글 크롬만 테스트해봤다는 것도 말씀드리고 싶네요.여기 jsfidle이 있습니다: http://jsfiddle.net/ADCKk/

브라우저 너비가 비디오 너비보다 작은 경우에는 비디오 크기가 줄어들지 않습니다.이 CSS를 사용해 보십시오(#bgvid가 비디오의 ID임).

#bgvid {
     position: fixed;
     top: 50%;
     left: 50%;
     min-width: 100%;
     min-height: 100%;
     width: auto;
     height: auto;
     transform: translateX(-50%) translateY(-50%);
     -webkit-transform: translateX(-50%) translateY(-50%);
}

저도 이 솔루션을 게시할 예정입니다. 제가 이 문제를 가지고 있었지만 다른 솔루션이 제 상황에 맞지 않았기 때문입니다.

나는 적절하게 시뮬레이션을 한다고 생각합니다.background-size:cover;요소 배경-이미지 속성 대신 요소의 CSS 속성을 사용하면 이미지 가로 세로 비율을 현재 창 가로 세로 비율과 비교해야 하므로 크기에 상관없이(그리고 이미지가 더 넓은 경우에도) 창이 창을 채우고 있습니다(그리고 중심을 맞춥니다).그게 요구사항이었는지는 모르겠지만)...

단순성을 위해 이미지를 사용하면 비디오 요소도 잘 작동할 것이라고 확신합니다.

먼저 요소 가로 세로 비율을 가져온 다음(로드된 후) 창 크기 조정 핸들러를 연결하고 초기 크기 조정을 위해 한 번 트리거합니다.

var img = document.getElementById( "background-picture" ),
    imgAspectRatio;

img.onload = function() {
    // get images aspect ratio
    imgAspectRatio = this.height / this.width;
    // attach resize event and fire it once
    window.onresize = resizeBackground;
    window.onresize();
}

그런 다음 크기 조정 핸들러에서 먼저 창의 현재 가로 세로 비율을 이미지의 원래 가로 세로 비율과 비교하여 너비 또는 세로 높이를 채울지 결정해야 합니다.

function resizeBackground( evt ) {

// get window size and aspect ratio
var windowWidth = window.innerWidth,
    windowHeight = window.innerHeight;
    windowAspectRatio = windowHeight / windowWidth;

//compare window ratio to image ratio so you know which way the image should fill
if ( windowAspectRatio < imgAspectRatio ) {
    // we are fill width
    img.style.width = windowWidth + "px";
    // and applying the correct aspect to the height now
    img.style.height = (windowWidth * imgAspectRatio) + "px";
    // this can be margin if your element is not positioned relatively, absolutely or fixed
    // make sure image is always centered
    img.style.left = "0px";
    img.style.top = (windowHeight - (windowWidth * imgAspectRatio)) / 2 + "px";
} else { // same thing as above but filling height instead
    img.style.height = windowHeight + "px";
    img.style.width = (windowHeight / imgAspectRatio) + "px";
    img.style.left = (windowWidth - (windowHeight / imgAspectRatio)) / 2 + "px";
    img.style.top = "0px";
}

}

이 접근법은 단지 css와 html을 사용합니다.실제로 비디오 아래에 div를 쉽게 쌓을 수 있습니다.크기를 조정하는 동안에는 표지가 중심에 있지 않습니다.

HTML:

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"> 
</script>
</head>
<body>
<div id = "contain">
<div id="vid">
    <video autoplay>
        <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" type="video/mp4" />
    </video>
</div>
</div>
</body>
</html>

CCS:

/*
filename:style.css
*/
body {
    margin:0;
}

#vid video{
position: absolute; 
right: 0; 
top: 0;
min-width: 100%; 
min-height: 100%;
width: auto; 
height: auto; 
}

#contain {
width:100%;
height:100%;
zoom:1%;/*Without this the video will be stretched and skewed*/ 
}

@히든 홉스

이 질문은 6일 후에 끝나는 히든 홉스의 +100 명성에 상당하는 공개 현상금을 가지고 있습니다.유연한 CSS 전용 솔루션을 얻기 위한 뷰포트 유닛의 혁신적인 사용.

당신은 이 질문에 CSS 전용 솔루션에 대한 현상금을 개설했으니 제가 한번 시도해 보겠습니다.이와 같은 문제에 대한 저의 해결책은 고정 비율을 사용하여 동영상의 높이와 너비를 결정하는 것입니다.저는 보통 부트스트랩을 사용하는데, 필요한 CSS를 거기서 추출해서 사용하지 않고 작동하게 했습니다.이 코드는 무엇보다도 내장된 비디오를 올바른 비율로 중앙에 배치하기 위해 이전에 사용한 코드입니다.에 효과가 있을 것입니다.<video>그리고.<img>요소들도 여기에 관련이 있는 것은 맨 위에 있는 것이지만, 다른 두 개도 이미 준비해 두었기 때문에 당신에게 주었습니다. :) :)

jsfidle 전체 화면 예제

.embeddedContent.centeredContent {
    margin: 0px auto;
}
.embeddedContent.rightAlignedContent {
    margin: auto 0px auto auto;
}
.embeddedContent > .embeddedInnerWrapper {
    position:relative;
    display: block;
    padding: 0;
    padding-top: 42.8571%; /* 21:9 ratio */
}
.embeddedContent > .embeddedInnerWrapper > iframe {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
    border: 0;
}
.embeddedContent {
    max-width: 300px;
}
.box1text {
    background-color: red;
}
/* snippet from Bootstrap */
.container {
    margin-right: auto;
    margin-left: auto;
}
.col-md-12 {
    width: 100%;
}
<div class="container">
    <div class="row">
        <div class="col-md-12">
            Testing ratio AND left/right/center align:<br />
            <div class="box1text">
                <div class="embeddedContent centeredContent">
                    <div class="embeddedInnerWrapper">
                        <iframe allowfullscreen="true" allowscriptaccess="always" frameborder="0" height="349" scrolling="no" src="//www.youtube.com/embed/u6XAPnuFjJc?wmode=transparent&amp;jqoemcache=eE9xf" width="425"></iframe>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            Testing ratio AND left/right/center align:<br />
            <div class="box1text">
                <div class="embeddedContent rightAlignedContent">
                    <div class="embeddedInnerWrapper">
                        <iframe allowfullscreen="true" allowscriptaccess="always" frameborder="0" height="349" scrolling="no" src="//www.youtube.com/embed/u6XAPnuFjJc?wmode=transparent&amp;jqoemcache=eE9xf" width="425"></iframe>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            Testing ratio AND left/right/center align:<br />
            <div class="box1text">
                <div class="embeddedContent">
                    <div class="embeddedInnerWrapper">
                        <iframe allowfullscreen="true" allowscriptaccess="always" frameborder="0" height="349" scrolling="no" src="//www.youtube.com/embed/u6XAPnuFjJc?wmode=transparent&amp;jqoemcache=eE9xf" width="425"></iframe>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

당신은 이 CSS 코드를 시도해 볼 수 있습니다.

video {
object-fit: cover;
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
}

티모시 라이언 카펜터의 답변이 설명되지 않는 위치의 의견에 답변하는 것.cover배경을 으로, 과 같은 빠른 CSS수정을 경을중심로으배저, 다같은빠른다과음니 CSS정합공.

CSS:

margin-left: 50%;
transform: translateX(-50%);

이 두 줄을 추가하면 모든 요소가 가운데에 배치됩니다.더 좋은 것은 HTML5 비디오를 처리할 수 있는 모든 브라우저도 CSS3 변환을 지원하므로 항상 작동합니다.

완전한 CSS는 다음과 같습니다.

#video-background { 
    position: absolute;
    bottom: 0px; 
    right: 0px; 
    min-width: 100%; 
    min-height: 100%; 
    width: auto; 
    height: auto; 
    z-index: -1000; 
    overflow: hidden;
    margin-left: 50%;
    transform: translateX(-50%);
}

저는 티모시의 대답에 직접적으로 언급했을 것이지만, 그렇게 하기에는 충분한 평판이 없습니다.

여러분, 제게 더 좋은 해결책이 있습니다. 짧고 완벽하게 작동합니다.비디오에 사용했습니다.그리고 커버 옵션을 css로 완벽하게 에뮬레이트합니다.

자바스크립트

    $(window).resize(function(){
            //use the aspect ration of your video or image instead 16/9
            if($(window).width()/$(window).height()>16/9){
                $("video").css("width","100%");
                $("video").css("height","auto");
            }
            else{
                $("video").css("width","auto");
                $("video").css("height","100%");
            }
    });

만약 당신이 뒤집으면, 당신은 억제될 것입니다.

그리고 여기에 css가 있습니다. (중심 포지셔닝을 원하지 않으면 사용할 필요가 없으며, 부모 div는 "위치: 상대적"이어야 합니다.)

CSS

video {
position: absolute;
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
top: 50%;
left: 50%;}

저는 방금 이것을 해결했고 공유하고 싶었습니다.이것은 부트스트랩 4에서 작동합니다.은 작니다합동에서와 함께 합니다.img하지만 저는 그것을 테스트하지 않았습니다.video의 HAML과 SCSS입니다.

HAML
.container
  .detail-img.d-flex.align-items-center
    %img{src: 'http://placehold.it/1000x700'}
SCSS
.detail-img { // simulate background: center/cover
  max-height: 400px;
  overflow: hidden;

  img {
    width: 100%;
  }
}

/* simulate background: center/cover */
.center-cover { 
  max-height: 400px;
  overflow: hidden;
  
}

.center-cover img {
    width: 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="center-cover d-flex align-items-center">
    <img src="http://placehold.it/1000x700">
  </div>
</div>

오래된 질문입니다. 하지만 누군가 이것을 본다면, 제 생각에 가장 좋은 대답은 동영상을 애니메이션 GIF로 변환하는 것입니다.이렇게 하면 훨씬 더 많은 제어를 할 수 있고 이미지처럼 처리할 수 있습니다.동영상을 자동으로 재생할 수 없기 때문에 모바일에서 작동하는 유일한 방법이기도 합니다.나는 질문이 그것을 하기 위해 묻는 것이라는 것을 압니다.<img>태그, 하지만 나는 그것을 사용하는 것의 단점을 정말로 보지 않습니다.<div> 는것하기background-size: cover

저도 이 문제가 있었고 다음의 CSS로 해결했습니다.

#video-container {
    overflow: hidden;
}

#video{
    width: 100%;
    position:absolute; 
    top: 0; 
    right: 0; 
    z-index: -1; 
}

언급URL : https://stackoverflow.com/questions/10797632/simulate-background-sizecover-on-video-or-img