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

Click on the button to reveal the hidden content within the div, and then smoothly scroll down to view

I have a footer div that is present at the bottom of every page on our site. I've added a button to expand this div, but I'm looking for a way to automatically scroll the page down so that the user can view the expanded content without manually s ...

Email the jQuery variable to a recipient

I'm facing an issue with sending a jQuery variable containing HTML and form values via email using a separate PHP file with the @mail function. My attempt involves using the jQuery $.ajax function on form submit to send this variable, but unfortunate ...

Exploring Nested Objects in ReactJS

When I make a call to , I am able to access properties such as active_cryptocurrencies and active_markets, but for some reason, total_market_cap and total_volume_24h are returning as undefined. import React, { Component } from "react"; import { render } f ...

`Issues encountered with resizing the menu``

Looking to create a unique restaurant horizontal list bar for my application. The goal is to have a horizontal menu that displays 3 options on the screen at a time, with the middle one being the largest and the two flanking it smaller in size. As I scroll ...

The resolvers contain the Query.Mutation but it is not specified in the schema

const { ApolloServer, gql } = require('apollo-server-express'); const express = require('express'); const port = process.env.PORT || 4000; const notes = [ { id: '1', content: 'This is a note', author: 'Adam ...

jQuery function to display character count updating with each keystroke, indicating 1 character is remaining when none

I have implemented a feature using jQuery to display the remaining characters in a text input field. The functionality is working well, but I am encountering an issue where it shows 1 character remaining when it reaches 0, even though it doesn't allow ...

Substitute the division

Can I make the old div change its position and move to the side when I add a new div? And can all the old divs be hidden when adding four new divs? This is for my full news website and I want this applied to all four pages. First page: More pages: 2 pag ...

Steps for sharing a word file between two users

Can someone help me with sending a file to another user and providing them with a download link? I have already attached the file to the database table of the recipient, but now I need to figure out how to allow them to download and view it. I've hear ...

Organizing a NodeJS module - properties and functions

I've been struggling to structure my NodeJS application with modules, and after hours of searching, I haven't found a definitive answer. Let's say I want to create a "user" module for creating new users in my code: var newUser = new User(); ...

React Material-UI eliminates the 'content' property from the CSS pseudo-element

Creating a React MUI Box and styling it like this: <Box id='my-box' sx={{ '&::before': { content: 'Yay! ', backgroundColor: 'red' } }} >Life is beautiful</Box> However, duri ...

How well does position:fixed function in Internet Explorer versions 7, 8, and 9?

Before diving into using position:fixed, I'd like to confirm if it works well in Microsoft browsers. Thank you. ...

What are the alternatives to invoking a server-side C# method from JavaScript without using a WebMethod or UpdatePanel?

I am looking for alternatives to using an update panel. The common WebMethod approach is causing errors with the code below: private string currentHtml() { StringWriter str_wrt = new StringWriter(); HtmlTextWriter html_wrt = new Htm ...

I want to save the information for "KEY" and "textValue" in JSON format and then return it as a response when I make a request to app.get("/api"). How can I achieve this?

Working with GCP Document AI using Node.js and react.js, I have created a JSON structure (var jsonResult) in the provided code. In the for loop, I am extracting key and text value data by using console.log(key); and console.log(textValue);. However, my g ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...

What is the most effective method for identifying the initial timestamp for each day, week, or month within a collection of timestamps?

I am dealing with a lengthy array of sorted timestamps representing stock price quotes. These timestamps have minimal resolution, meaning that each timestamp is at least 1 minute bigger than the previous one. However, there can be gaps during the day, espe ...

Issue with the JSON response in MVC 4

I have been struggling to bind JSON values to specific text boxes. It works with dynamically created textboxes but not with static ones that are already present. I've been stuck on this issue for 2 days and despite searching the internet, I couldn&apo ...

Retrieve the element that triggered the event listener within Nuxt

I am currently developing a Nuxt project where I have set up my component using the code below. The select-parent-container has a click event attached to it. Whenever this event is triggered, I need to identify and return the specific parent container that ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

The absence of a React JS button on the page

I'm in the process of creating a React demo application and I've come across this component: var MediaList = React.createClass({ displayName: 'MediaList', getInitialState: function() { return { tweets: getTweets(numTweets) ...

Connecting an admin dashboard to a MERN e-commerce application: A step-by-step guide

In the process of developing an e-commerce platform, I find myself using React.js for the frontend and Node.js/Express.js for the backend. My current challenge lies in creating a seamless dashboard to manage items within the app. One possible solution wo ...