Search code examples
heightbootstrap-5

Bootstrap 5 iframe unresponsive height


iframe in bootstrap card scales with width but not height how do I make the height responsive as well?

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="row no-gutters">
    <div class="col-12">
      <div class="card mt-4" style="width: 100%;">
        <div class="embed-responsive embed-responsive-4by3">
          <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/vlDzYIIOYmM" style: width="100%" height="100%" allowfullscreen></iframe>
        </div>
        <div class="card-body">
          <h5 class="card-title">Card title</h5>
          <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
          <a href="#" class="btn btn-dark">Go somewhere</a>
        </div>
      </div>
    </div>
  </div>
</div>


Solution

  • From the bootstrap documentation: (https://getbootstrap.com/docs/5.2/helpers/ratio/#example)

    Wrap any embed, like an <iframe>, in a parent element with .ratio and an aspect ratio class. The immediate child element is automatically sized thanks to our universal selector .ratio > *.

    I also removed the unneeded (hardcoded) width/height attributes.

    See sample code below:

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="container-fluid">
      <div class="row no-gutters">
        <div class="col-12">
          <div class="card mt-4">
            <!-- changes made from here -->
            <div class="ratio ratio-16x9">
              <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/vlDzYIIOYmM" allowfullscreen></iframe>
            </div>
            <!-- to here -->
    
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
              <a href="#" class="btn btn-dark">Go somewhere</a>
            </div>
          </div>
        </div>
      </div>
    </div>