How can I automatically center a Vimeo iframe vertically without having to manually adjust the position?

I'm trying to adjust a popular fluid jQuery script so that it can automatically center a vimeo video vertically, without any black bars. A little horizontal cropping is acceptable. Here is my current code:

HTML

<div class="container">
    <div class="videoWrapper">
        <iframe class="js-resize" src="http://player.vimeo.com/video/80836225?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1" frameborder="0" scrolling="no" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
    </div>
</div>

CSS

.container {
    height: 100%;
    width:auto;
}
.videoWrapper {
    position: relative;
    height: 100%;
    width: auto;
}

.videoWrapper iframe,
.videoWrapper embed,
.videoWrapper object {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
}


html, body {
  margin: 0px;
  padding: 0px;
}

JS

// jQuery 1.6.2

// Find all YouTube videos
var $allVideos = $("iframe[src^='http://player.vimeo.com'], iframe[src^='http://www.youtube.com']"),

    // The element that is fluid width
    $fluidEl = $("body");

// Calculate and store aspect ratio for each video
$allVideos.each(function() {

  $(this)
    .data('aspectRatio', this.height / this.width)
    .removeAttr('height')
    .removeAttr('width');

});

// Resize videos on window resize
$(window).resize(function() {

  var newWidth = $fluidEl.width();

  // Resize videos based on aspect ratio
  $allVideos.each(function() {

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

  });

}).resize();

Answer №1

Give this a shot:

To adjust the height in your CSS, use the following code:

videoWrapper iframe {height:XXXXpx;}

Replace XXXX with your desired height value in pixels.

Next, include the following code:

videoWrapper iframe {margin-top:-XXpx;}

In this case, -XXpx represents half the value of the total height.

Lastly, within your videowrapper iframe, add:

videoWrapper iframe {position:absolute; top:50%;}

Your final setup should look like this:

.videoWrapper {
position: relative;
height: 100%;
width: auto;
}

.videoWrapper iframe,
.videoWrapper embed,
.videoWrapper object {
position: absolute;
width: 100%;
height: XXXXpx;
margin-top: -XXpx;
left: 0;
top: 50%;
}

This adjustment will center the object vertically and horizontally on the screen. Give it a try and let me know if it works for you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enable automatic playback of HTML5 video with the sound on

I want to add an autoplay video with sound on my website, but I'm running into issues with newer browsers like Chrome, Mozilla, and Safari blocking autoplay if the video doesn't have a 'muted' attribute. Is there a clever HTML or Javas ...

Trigger jQuery form submission when checkbox is clicked

I am looking to enhance my form submission process by triggering it whenever checkboxes are clicked. I already have ajax set up with Rails to handle this. My goal is for the form to be submitted every time a checkbox is clicked, even if it is checked and u ...

What could be causing a parse error and missing authorization token in an AJAX request?

I recently wrote some code to connect a chat bot to Viber using the REST API. The main part of the code looks like this -: $.ajax({ url : url , dataType : "jsonp", type : 'POST', jsonpCallback: 'fn', headers: { 'X-Viber-Auth- ...

Combining JSON objects in a Pentaho JavaScript JSON by matching keys to merge with an existing JSON document

My goal is to construct a Json document by breaking it down into smaller pieces, with each piece containing the necessary keys to insert the smaller Json bits into the correct json structure. As I am relatively new to JavaScript and still in the process of ...

Encountering error: Unknown flag '-p' when trying to execute yarn build:prod in Angular 6

For the past two days, I have been encountering a problem. After updating Angular from version 4 to 6, I am unable to generate a production build. Commands like yarn build and yarn dev are functioning properly. However, when I execute yarn build:prod, I re ...

What sets apart the definition of isolated scope variables for an Angular directive when done within {} as opposed to in

When working with Angular directives, I am aware that I can assign an isolated scope by adding '=' or '@' or '&' in the {} to define variables. However, it seems like this is not required within the link function. For example: ...

I'm having trouble utilizing toastify.js after installing it via npm. I keep receiving the error message "Failed to resolve module specifier." Any advice

Currently, I am attempting to utilize Toastify-js, a library designed for toast type messages, by installing it through npm. In the provided documentation, following the execution of the installation command, there is a direction that states: - To begin ...

Implementing Jquery: Show a class after clicking the button and then remove it

I am looking for a way to display a class when a button is clicked and then remove it when the same button is clicked again, repeatedly. I have multiple buttons so I cannot use the toggle function as it does not provide the desired behavior. I have tried v ...

What could be causing WidgEditor, the JavaScript text editor, to fail to submit any values?

After clicking submit and attempting to retrieve text from the textarea, I am encountering a problem where the text appears blank. The reason for this issue eludes me. function textSubmit() { var text = $("#noise").val(); console.log(text); consol ...

Single-Page Design Ascend

I'm facing a dilemma with my one-page website layout project. Instead of the conventional scroll down effect, I'd like to implement a design similar to www.xsbaltimore.com where users have to scroll up to view other sections. However, I'm un ...

How to modify the color of the placeholder text in a select dropdown using Material-ui

I have a material-ui select component that displays a dropdown menu of options for the user to choose from. The placeholder text, which currently reads "select option," appears in light grey to prompt the user to make a selection. However, I am concerned t ...

Executing function with ng-click in AngularJS only on the second click of the button

Currently, I am studying AngularJS and working on an exercise that involves using the ng-click function. Strangely, I am only able to view the result after clicking upload for the second time. I am trying to display my json content but it's not workin ...

jQuery's outerHeight() and height functions may experience flickering or fail to update properly when the window is resized to an odd number

Two elements are placed side by side on a webpage. One element, with a fixed size of 100vh, is named .hero-half, while the other element, holding text of varying lengths, is fluid and labeled as .project-details. When the text container extends beyond the ...

Utilize JavaScript's $.post function to export PHP $_POST data directly into a file

After spending hours trying to figure this out, I've come to the realization that I am a complete beginner with little to no knowledge of what I'm doing... The issue I'm facing is related to some JavaScript code being triggered by a button ...

Redirecting in AngularJS after a successful login操作

Is there a way to redirect users back to the original page after they login? For example, if a user is on a post like www.example.com/post/435 and needs to log in to "like/comment" on the post, how can I automatically redirect them back to that specific po ...

Submitting an intricate item to a WCF REST API using JQuery

Currently, I am attempting to send a complex object to my WCF REST service. Utilizing this method seems to be the most straightforward way to upload a Stream type object along with other parameters to an endpoint simultaneously. Service: [OperationContra ...

Common Error for Novice HTML/CSS Learners

I am currently enrolled in an introductory web design course on Treehouse, and I have encountered a problem with centering a class in HTML using CSS. Despite following the instructions closely, my code is not displaying correctly. Can someone please review ...

Steps to showcase a form on a webpage using a button

My webpage features an HTML table with a table navigation bar that allows users to add items or inventory. However, when the "add item" button is clicked, a form appears below the table instead of on top of it. I want the form to display itself right on to ...

Utilizing Angularjs for dynamic data binding in HTML attributes and style declarations

Can someone help me figure out how to use an AngularJS model as the value for an HTML attribute? For example: <div ng-controller="deviceWidth" width={{width}}> </div> Additionally, how can I achieve this within <style> markup? Where ...

Navigating between sibling components in Angular 1.5 using the component router

Is there a way to use the new component router in Angular 1.5 to display the sibling component alongside the main one within the ng-outlet directive? I am looking to showcase both the Detail View and the List View at the same time. Based on my understandin ...