首页 > 解决方案 > 如果视口上没有足够的空间,视频元素将低于前一个元素

问题描述

我正在尝试将视频元素动态添加到 div 中,每个视频元素的宽度为 50vh。因此,从技术上讲,在 2 个视频元素之后,第 3 个视频元素将位于屏幕左侧下方。

我努力了:

.views-container {
    padding: 0;
    margin: 0;
    font-size: 0;
}

.video-inset {
    outline: unset;
    position: relative;
    margin:0; 
    padding:0;
}

<div class="views-container background-black" id="container"></div>

和 JS

// Current condition is for 3 video elements but could be more
// height width added dynamically and could be different depending on number of elements
// 3 video elements in a row (33.33vw width) if greater than 15 video elements

const container = document.getElementById('container')

const video = document.createElement('video');
video.style.height = 50+"vh"
video.style.width = 50+"vw"

container.append(video);

它只能在 2 个容器之前正常工作。请帮忙。

标签: htmlcss

解决方案


您可以display: grid;.views-container. 我使用了 和 的宽度和50vw高度50vh。您需要将2(列数)更改repeat(2, 1fr)为另一个数字。

const container = document.getElementById('container');

let n = 20;  //Total number of videos

for (var i = 1; i <= n; i++) {
  const video = document.createElement('video');
  if(n > 15){
  container.style.gridTemplateColumns = "repeat(3, 1fr)";
    video.style.height = "33.33vh";
    video.style.width = "33.33vw";
  } else{
    video.style.height = "50vh";
    video.style.width = "50vw";
  }
  video.src = "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"
  container.append(video);
}
.views-container {
  padding: 0;
  margin: 0;
  font-size: 0;
  display: grid;
  grid-template-columns: repeat(2, 1fr)
}


.video-inset {
  outline: unset;
  position: relative;
  margin: 0;
  padding: 0;
}
<div class="views-container background-black" id="container"></div>


推荐阅读