Ensure that the video is properly positioned within the background when utilizing the background-size cover property

I am currently working on a project that requires me to position a video clip on a specific section of the background image, ensuring that the video always appears on top of the phone's screen. The responsive background image is constantly changing. How can I maintain the relative position of the video container to ensure it stays in place?

CSS:

.main{
    background-image: url("../images/moshe.jpg"); 
    background-attachment: fixed;
    background-position: center center;
    background-size: cover;
    height: auto;
    left: 0;
    min-height: 100%;
    min-width: 100%;
    position: absolute;
    top: 0;
    width: auto;
}
.overlay{
    position: fixed;
    position: absolute;
    top: 30%;
    left: 30%;

}

HTML:

<!-- video -->
    <div class="embed-responsive embed-responsive-16by9 overlay">
        <video muted autoplay loop class="embed-responsive-item" width="100">
            <source src="images/time.mp4" type=video/mp4>
        </video>
    </div>

Answer №1

CSS Solution Using Viewport Units

A pure CSS solution is available for achieving this effect, but there are some considerations to keep in mind:

  1. It relies on using the vh and vw units, which may not be fully supported in all browsers, but support is getting better over time. This demonstrates the power of CSS3!

  2. For this solution to work effectively, your target image needs to be sized relative to the viewport dimensions.

  3. This solution also leverages media queries, a common technique for responsive web design.

Some adjustments might be necessary to fine-tune the positioning of the video element, but it has shown compatibility with modern browsers in my testing.


Insight Into Implementation

The critical aspect to understand here is how browsers handle scaling when using the "cover" property on an image. The transition occurs based on the ratio between viewport width and height, specifically suited to the image's aspect ratio.

While I'd like to claim mathematical precision in determining the threshold set in @media (min-width: 178vh), I confess it involved trial and error. By calculating the ratio from the original image dimensions of 3264 x 1836 (resulting in 1.7777777778), converting it to a hundredth value due to vh and vw unit scale, gives us approximately 178. Adjustments will be needed if the image dimensions change, requiring updates to the media query selector.

Further tweaks involve gauging the portion of the viewport occupied by the video in terms of vh and vw. Experimentation led me to these values, amid the confounding influence of beer-fueled problem-solving methods... quite inexplicable.


Implications and Workarounds

Upon additional testing, it seems that Webkit struggles with interpreting vh within media queries, reluctance seemingly towards max-width scenarios. Exploration reveals potential recourse via vmin and vmax implementations.

Later Realizations...

Confirming suspicions, Webkit disappoints once more regarding its handling of vh and vw in certain contexts. While the browser comprehends these units elsewhere, a blind spot persists in media queries, compounding frustrations among developers.

An alternative workaround involves utilizing the orientation property within the media query. Although not foolproof, it mitigates failures barring square-ish viewports. Below, you'll find the revised code reflecting this adjustment.


Conclusion and Contingencies

If I were tasked with implementing this amidst existing browser disparities, I'd opt for the CSS approach supplemented by JavaScript intervention for unsupportive environments. Utilizing techniques like window.matchMedia or libraries such as Enquire.js facilitates comprehensive cross-browser adaptability.

The code snippet now includes a JavaScript fallback mechanism, warranting refinement to avoid inadvertent class overrides on HTML elements. Prudence dictates exploring established solutions integrating event listeners and class manipulation to ensure seamless compatibility across diverse browsing environments.

// Credit to http://stackoverflow.com/questions/3437786/#answer-11744120
var viewportDimensions = function(){
  var w = window,
      d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0];
  return {
    w: w.innerWidth || e.clientWidth || g.clientWidth, 
    h: w.innerHeight|| e.clientHeight|| g.clientHeight
  };
};

window.matchMedia && (function(){
  var test = window.matchMedia('screen and (min-width: 0vh)'), f;
  // Failure is rare, predominantly affecting incompatible vh support in media queries.
  if ( !test.matches ) {
    // Respond to resize events
    window.addEventListener('resize', (f=function(e){
      // Acquire viewport dimensions
      var vpd = viewportDimensions();
      // Implement equivalent logic compared to the media query
      if ( vpd.w > (1.78 * vpd.h) ) {
        document.documentElement.className = 'min-width-178vh';
      }
      else {
        document.documentElement.className = 'max-width-178vh';
      }
    }));
    // Initial invocation
    f();
  }
})();
/* Centralizing coordinates, aligning with the fixed nature of "cover" usage */
.layer {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 1px;
    height: 1px;
}

/* Primarily reliant on viewport height, mirroring "cover" behavior during image expansion */
.video {
    position: absolute;
    width: 25.5vh;
    left: -50.5vh;
    top: -22.8vh;
    background: #F00;
}

/* Addressing partial Webkit compatibility issue, adjusting calculations for non-squareish layouts */
@media screen and (orientation: landscape) {
  .video {
    top: -12.75vw;
    left: -28.5vw;
    width: 14.2vw;
  }
}

/* Adaptation for changing scaling/cropping dynamics, pivot shifted towards viewport width */
@media screen and (min-width: 178vh) {
  .video {
    top: -12.75vw;
    left: -28.5vw;
    width: 14.2vw;
  }
}

/* Reversing prior adjustments to accommodate Firefox rendering after Webkit rectification */
@media screen and (max-width: 178vh) {
  .video {
    width: 25.5vh;
    left: -50.5vh;
    top: -22.8vh;
  }
}

/* Overriding media queries through JavaScript fallback triggers */
.min-width-178vh .video {
  top: -12.75vw !important;
  left: -28.5vw !important;
  width: 14.2vw !important;
}
.max-width-178vh .video {
  width: 25.5vh !important;
  left: -50.5vh !important;
  top: -22.8vh !important;
}

/* Initialization styles for structural setup */
.main {
    top: 0;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
}

.inner {
    position: absolute;
    background: url("http://www.codelamp.co.uk/so/cover-video-pos-bg.jpg") no-repeat center center / cover; 
    background-color: #000;
    width: 100%;
    height: 100%;
}
<div class="main">
    <div class="inner"></div>
    <div class="layer">
        <div class="video">
            <video width="100%"></video>
        </div>
    </div>
</div>

Answer №2

Initially, your css contains some redundancy.

.overlay{
    position:fixed;       /*  <--- This line  */
    position: absolute;   /*  <--- And This line  */
    top: 30%;
    left: 30%;
}

In this scenario, the position:absolute will be prioritized since it appears later.

Assuming the video element is correctly positioned with top: 30% and left: 30%, try assigning a low z-index value (such as z-index: -100) to move it backward.

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

What is the best way to add prefixes to my SCSS style sheets?

After attempting to add prefixes to my scss files, I came across the autoprefixer tool. However, I discovered that it only supports CSS files. Is there a way to utilize autoprefixer with scss files? Here are the commands for Autoprefixer: npm install post ...

Manipulating Columns with Bootstrap 4

What I'm Looking For: Desktop: B A Mobile: A B This is the HTML structure I have: <div class="row"> <div class="col-md-7 col-sm-7 push-md-5"> A </div> <div class="col-md-5 col-sm-5 pull-md-7"> ...

"What is the process for creating a single line border around a pandas DataFrame using df.to_html method

After exporting a pandas dataframe as an HTML table to Outlook, I noticed that the double cell borders are not aesthetically pleasing. I am seeking assistance in changing them to a single line border. Please refer to the attached screenshot and code snip ...

Transform Ajax response into dropdown menu option

I have made an ajax call and received HTML as a response. Now, I need to convert this output into options and add them to select tags on my webpage. <div class="views-element-container"> <div class="view view-contact-view-id-conta ...

`Modified regions determined by cursor location`

I am working with a split layout featuring two columns, and I need the ability to make each column separately scrollable. Due to using a specialized scroll-to function, I cannot use overflow-y: scroll; or overflow: auto;. I am looking for alternative solut ...

Arrange the HTML DOM elements in the order of their appearance in a list

Is it possible to rearrange the order of <div> and its elements based on database information? For example, consider the following HTML structure: <div id="container"> <div id="A"> Form elements for A</div> <div id="B"& ...

Pressing the up arrow in Javascript to retrieve the most recent inputs

Is there a way to retrieve the most recent inputs I entered in a specific order? For example: I have an array with 20 elements, and every time I enter something, I remove the first element from the array and add the new input at the end. So, when I press ...

Retrieve the Data from Input Fields with Matching Classes and Transmit to a Script Using AJAX Request

I am working on a form that includes multiple input fields: <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="da ...

Flexbox is not properly repeating elements horizontally

I am struggling to align text boxes horizontally within ngFor loop, and I can't seem to pinpoint the mistake. Here is the HTML code from the parent component: <div class="maintenance-section"> <div class="yearly"> ...

Looking to activate a button only when the checkbox is selected and in an enabled state

I'm struggling to make the button enable when the checkbox is checked and enabled. Additionally, it should be dependent on the textarea scroll above it. Once the checkbox is checked, the page needs to scroll up and down to activate the button. Here& ...

Steps for creating a table with a filter similar to the one shown in the image below

https://i.sstatic.net/zR2UU.png I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column for ...

The iteration count and stop code in CSS are failing to function correctly

Is there a way to make this loop once and then stay as is unless the page is refreshed? I've tried multiple methods I came across. Can you modify the code so I can see where the changes are being made? The goal is to have it display once and then per ...

What adjustments can be made to the Bootstrap code to prevent it from causing layout issues with the Signin Form and Footer?

Recently, I've encountered some challenges with the footer formatting on my website's home page and the sign-in form on a separate page. It appears that the Bootstrap framework at the top of the page is affecting these elements exclusively. How c ...

How to Use Vue.js to Find the Nearest Div Element with a Specific

Below is the HTML code I am working with: <div id="app"> <div class="image"> <div class="overlay"> <p>Some overlay text</p> </div> <img src="https://placeimg.com/640/480/any" class="img-fluid"> ...

Should the value exceed the designated width of the combobox, it should be displayed across multiple lines

Having an issue where, when I set the width of the combobox and the value inside it is longer than expected, the full value isn't displayed. I am considering displaying the value on multiple lines to ensure the entire content is visible. Unfortunatel ...

Require an additional button to dynamically load more content and shift all existing elements further down the page

I am looking to implement a "load more" button for an Instagram feed on my website. My current approach involves increasing the height of a specific section while moving the rest of the page down. This is what I have tried: <script> $(document.ready ...

Tips for displaying multiple results from a MySQL query in a single .ejs file using Node.js and Express

Currently diving into Node.js and working on a web application, I am faced with the challenge of rendering twice in the same .ejs file. Consider the scenario presented in the following .ejs file: <table> <% rows.forEach(function(ind){ %> /* m ...

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

The redirection from HTTP or www to HTTPS is not functioning as expected

Redirecting all links to my website to the https:// domain is supposed to work flawlessly, but there are certain ways it doesn't quite function as expected. https://www.example.com --- works example.com --- works www.example.com --- encounters issu ...

Values are being set back to '1' within the popup dialog

After recently incorporating Twitter Bootstrap into my web app project, everything seemed to be going smoothly until I encountered an issue with a modal window. Following the Bootstrap documentation, I set up a button that triggers a modal window to appea ...