Instructions on how to properly align a Youtube video using the react-youtube package

I'm currently encountering an issue with my YouTube video display. I have managed to make it responsive, but it is stuck on the left side of the screen and I am unsure how to center it properly. I tried adjusting the padding, but it didn't work as expected.

Here is what I have tried:

import "../styles/SponsorUs.css";
import svg from "../assets/parcours.svg";
import React, { useState, useEffect } from "react";
import YouTube, { YouTubeProps } from 'react-youtube';

function Example() {
    const onPlayerReady: YouTubeProps['onReady'] = (event) => {
        event.target.pauseVideo();
    }

    const opts: YouTubeProps['opts'] = {
        height: '350',
        width: '640',
        playerVars: {
            autoplay: 1,
        },
    };

    return <div className='video-container'><YouTube videoId="Zu8MYX5h4x8" opts={opts} onReady={onPlayerReady} /></div>;
}

export function SponsorUs() {
    return (
        <div className='global'>
            <div className='titleSponsor'>
                { <img className='titleSponsorImg' src={svg} alt=''/>}
                <h1>Le 4l Trophy, c’est quoi?</h1>
                <p className='titleSponsorp1'>Le 4L Trophy est un raid étudiant organisé depuis plus de 20 ans au Maroc.
                    Il s'agit d'un défi sportif et humanitaire qui réunit chaque année des milliers d'étudiants
                    venus de toute la France et d'ailleurs. Le but ? Parcourir plus de 6000 kilomètres à bord de 4L,
                    tout en acheminant des fournitures scolaires pour les enfants défavorisés du Maroc.</p>
                <h1>Notre itinéraire </h1>
                <p className='titleSponsorp2'>Notre itinéraire pour le 4L Trophy est un véritable parcours du combattant!
                    Nous affronterons les routes les plus difficiles du Maroc, à travers les montagnes,
                    les déserts et les plaines arides. Nous serons confrontés à des défis physiques et mentaux,
                    mais nous sommes prêts à relever le défi!</p>
                { <img className='titleSponsorImg2' src={svg} alt=''/>}
                <h1>Trailer du 4L Trophy</h1>
                <Example />
                <h1>Vous êtes captivés par notre projet ? </h1>
            </div>
        </div>
    );
}

And here is the linked CSS:

.video-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
}

Thank you for your assistance. I believe there is a minor adjustment required, but I'm not certain where to make it.

Answer №1

To ensure the YouTube video is centered on the page, you can customize the CSS properties of the .video-container and .video-container iframe classes in the following manner:

.video-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* Adjust container height to match viewport height */
}

.video-container iframe {
  width: 80%; /* Set iframe width */
  height: 45vw; /* Adjust iframe height based on aspect ratio */
}

This CSS code configures the .video-container to use display: flex, justify-content: center, and align-items: center, effectively centering the video element both horizontally and vertically within the container.

The .video-container's height is set to 100vh to occupy the full viewport height, while the iframe's dimensions are fine-tuned for responsive video display.

You have the flexibility to modify the iframe's width and height values to suit your video size requirements.

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

In Javascript, merge two objects while maintaining their original references

Here's a basic illustration of my goal: data = {name: 'fred'}; newData = {}; newData.name = data.name; newData.name = 'ted'; console.log(data.name); // I expect this to be ted instead of fred I am wondering if it is feasible i ...

Expanding a website banner slide to fill the entire width of the page

Is there a way to ensure that the banner images in the website below flow seamlessly? Currently, it seems like the current image is cut off on the left and part of the previous image shows up in its place. I'd like the current image to occupy the ent ...

SlidingPane header in React disappearing behind Nav bar

Here is the code snippet from my App.js file: export class App extends React.Component { render() { return ( <BrowserRouter> <NavigationBar /> <Routes /> </BrowserRout ...

How to implement multiple layouts in React Router 4 based on the URL path?

Here's a simple example I'm working on. export default class AppRouter extends Component { render() { return ( <div className="website-wrapper"> <Switch> <MainLayout> <Route exact pa ...

Issue in Ionic 3 where ion-list does not scroll vertically on iOS devices when ion-items are dynamically generated using ngFor within the ion-list

When using Ionic v3 to develop a hybrid app, I encountered an issue where ion-items within an ion-list generated using *ngFor are not scrollable on iOS devices. Strangely, this problem does not occur on Android devices. Here is the HTML code snippet: < ...

I'm exploring the world of JavaScript frameworks for the first time - where should I start?

I've recently delved into the world of JavaScript frameworks and I'm not sure where to start. Should I go with AngularJS, React, or Vue? I have been coding in JavaScript for the past 6 months. ...

Guide to easily incorporate state updates within an event using getDerivedStateFromProps

Struggling to transition from using the componentWillReceiveProps method to the static getDerivedStateFromProps, I am faced with a challenge of how to utilize the keyword this within the getDerivedStateFromProps function. Originally, my aim was to employ ...

Using JavaScript, you can add an article and section to your webpage

Currently, I am utilizing AJAX to showcase posts. My objective is to extract each property from a JSON object that is returned and generate an <article> for the title followed by a subsequent <section> for the content. While I can successfully ...

contrasting the typographical styles found in material/core versus material/system

Can you pinpoint the distinctions between typography in material/core and typography in material/system? What is the reasoning behind them originating from separate packages? And how do they differ in terms of application? Another aspect to explore is the ...

Could anyone assist me in activating code folding with react-codemirror2?

As I work on my web application, I've integrated react-codemirror2 to showcase JSON data. However, as the JSON files grow in size, navigating through the data becomes cumbersome. I am looking to introduce code folding to improve user experience, but I ...

"I'm facing an issue with aligning elements in my ReactJS application using CSS Flexbox. Despite setting up a flexbox layout, I am unable to

Despite setting up a flexbox to align my elements, I am struggling with vertical centering on my page. I have made sure to use a container for the page and set brute size with viewport units. Here is my sandbox: https://codesandbox.io/s/rlk3j68pmq. Belo ...

Dynamic Dropdown Options in Angular 6 HTML Input Field

Looking to create an interactive HTML5 input field that guides the user with their input. Consider a scenario where the user is required to follow a specific grammar while entering text: rule: <expression> {<op><expression>} expression: ...

Guide to properly deserializing a JSON string into a class with a nested List of different class members

I have a scenario where I am sending a JSON stringified "View" object from the browser to an ASP.Net Page Method using Jquery's $.Ajax(). The issue I am facing is that while the Javascript deserialization is successful for all the strings and integers ...

Is there a way to prevent users from selecting certain days in ion-datetime?

After searching through the official documentation, I couldn't find a solution. I am in need of a function similar to the jQuery datepicker beforeshowday function. My goal is to disable all weekends (Saturday and Sunday) in upcoming dates so that user ...

Authentication Error: CSRF cookie not detected - Please log in again to access the /login/ page using REACT and DJANGO

After successfully developing the frontend using React and backend with Django, everything was functioning flawlessly on localhost. However, upon deploying the frontend on Heroku and attempting a POST request to log in (with the backend still running on lo ...

display a loading spinner for number input fields in HTML5

In my HTML5 project, I am currently utilizing a numeric control (input type="number"). The default behavior displays the spinner (up and down arrows) only on hover. Is there a way to make the spinner permanently visible using CSS or another method? ...

Using `new Date(device.timestamp).toLocaleString()` in React with typescript results in an invalid date

The timestamp I am receiving is in unix time format. {devices.map((device, index) => { return ( <tr key={index} className="bg-white border-b "> <td className="py-4 px-6"> {getSensor ...

What is the best way to align a checkbox and text in the same row within a Mailchimp embedded form?

I am troubleshooting a styling issue with my Mailchimp form that has groups. The problem I'm encountering is that the checkboxes are displaying on one line while the text appears on the next line in an unordered list format. To see the issue for yours ...

Error: Invalid argument type

I'm encountering difficulties retrieving data from an API as I delve into learning Angular 2. The error message I am facing is: url.js:106 throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'url', 'string', url); Typ ...

The border color of the text input is not changing as expected when in focus

Is there a way to change the border color of a text input field to blue when it is not selected and then change it to orange when the field is selected? input[type="text"]{ border: 1px solid blue; } input[type="text"]:focus{ border: 1px solid ora ...