【问题标题】:Bootstrap responsive video but with max-width AND centered引导响应视频,但具有最大宽度和居中
【发布时间】:2016-04-30 08:44:34
【问题描述】:

要为 YouTube 视频嵌入响应式 4x3 视频,Bootstrap 网站说这样做:

<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item youtube" src="…"></iframe>
</div>

但我希望视频的最大宽度为 400 像素。所以我定义了一个类:

.youtube {
    max-width: 400px;
    max-height: 300px;
}

我试过了,效果很好:

<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item youtube" src="…"></iframe>
</div>

但在我的一生中,我无法使这个最大宽度(但响应低于该最大值)iframe 居中。我已经尝试将.center-block 添加到.embed-responsive.embed-responsive-item,但它什么也没做。有什么想法吗?

【问题讨论】:

  • 您的视频 div 是否被一列和一行包围?如果有,它们的尺寸是多少?尝试在 jsfiddle 中为您的问题制作一个工作示例,以便更容易了解它为什么不起作用。
  • 是的!现在这样做。谢谢。一瞬间……

标签: twitter-bootstrap


【解决方案1】:

整个上午都在为此苦苦挣扎。我的视频是动态的,所以不能确定它们是 4x3。我的 Bootstrap 4/JQuery 解决方案

HTML:

<div class="form-row">
  <div class="col-sm-1 col-lg-3"></div>
  <div class="col-sm-10 col-lg-6 text-center">
    <!-- this code is in a foreach loop, hence @item.Link -->
    <iframe width="560" height="315" src="@item.Link"></iframe>
  </div>
  <div class="col-sm-1 col-lg-3"></div>
</div>

JQuery:

function resizeIframes() {
  var $allVideos = $('iframe');

  $allVideos.each(function () {
    $(this)
        .data('aspectRatio', this.height / this.width)

        // and remove the hard coded width/height
        .removeAttr('height')
        .removeAttr('width');
  });

  // When the window is resized
  $(window).resize(function () {
    // Resize all videos according to their own aspect ratio
    $allVideos.each(function () {
        var newWidth = $(this).parent().width();

        var $el = $(this);
        $el
            .width(newWidth)
            .height(newWidth * $el.data('aspectRatio'));
    });

    // Kick off one resize to fix all videos on page load
  }).resize();
}

resizeIframes();

【讨论】:

    【解决方案2】:

    我尝试在 jsfiddle 中进行演示,但它产生的结果与我的浏览器不同。四个小时后,我找到了解决办法。为了使 iframe 既居中又响应,请将 .text-center 添加到直接容器 div 并使 iframe 元素的位置相对:

    <div class="embed-responsive embed-responsive-4by3 text-center">
      <iframe class="embed-responsive-item youtube" src="…"></iframe>
    </div>
    

    这是.youtube 类:

    .youtube {
      max-width: 400px;
      max-height: 300px;
      position: relative !important;
    }
    

    完整的 HTML:

    <div class="container">
    <div class="row">
    <main class="col-sm-8 col-main">
    <article class="post-main ">
    <section>
    <div class="embed-responsive embed-responsive-4by3 col--12 text-center">
      <iframe class="embed-responsive-item youtube" src="https://www.youtube.com/embed/KPZ8HHRR1A0"></iframe></div>
    </section>
    </article>
    </main>
    </div><!-- /.row -->
    </div><!-- /.container -->
    

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 2014-04-09
      • 2017-09-02
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多