Search code examples
htmlcsscenter

CSS: center video behind div without affecting overall div layout?


I have a page with multiple divs. They've all been sized and positioned according to various criteria.

[div1]
[div2]
[div3]

Now there's been a request to place a video (of a set width/height) behind one of the divs.

[div1]
[div2 - now with background video]
[div3]

How can I do this without affecting the existing layout in any way?

Here's a fiddle with the starting point for what I'm trying to do:

https://jsfiddle.net/gzdjL8kx/

I want the blue box (which represents the video) to remain centered (vertically and horizontally) behind the yellow box, without affecting the layout of the yellow/red/orange boxes at all, and in such a way that the layout of the yellow/red/orange boxes can be changed and the blue box's position will adapt so that it remains centered behind yellow. The blue box should also remain centered even if its width/height is changed.

Given that fiddle, here's my desired outcome, but I don't know how to achieve it:

https://i.sstatic.net/8qgxY.png

Basically I want the blue box to be able to be positioned relative to the yellow box without affecting the other boxes at all. All my attempts to center it so far end ultimately up bumping the other boxes around too.


Solution

  • If you use position:absolute; on your video you'll remove it from the document flow, which stops it influencing the position of other relatively positioned divs.

    If you're aiming for a lightbox style popup for your video you can centre it in the viewport using the following:

    .yellow
    {
      width:250px;
      height:150px;
      margin:auto;
      background-color:yellow;
      position:relative;
    }
    .orange
    {
      width:500px;
      height:100px;
      margin:auto;
      background-color:orange;
    }
    .red
    {
      width:100%;
      height:150px;
      background-color:red;
    }
    .blue
    {
      width:320px;
      height:240px;
      background-color:blue;
      position:absolute;
      top:50%;
      left:50%;
      transform:translate(-50%, -50%);
    }
    <div class="orange">
    </div>
    
    <div class="yellow">
      <div class="blue"></div>
    </div>
    
    <div class="red">
    </div>