0

I've successfully gotten a video to properly fit inside a div and fill it completely all the time thanks to this SO answer.

I've modified the code just a bit but I'm stumped as to why this code works.

    video
        position: absolute
        opacity: 0.1
        z-index: 0
        top: 0px
        left: 50%
        min-width: 100%
        min-height: 100%
        right: 0px
        margin: auto
        width: auto
        height: auto
        overflow-x: hidden
        transform: translateX(-50%)

I don't get what the transform does and how to get it to fix to something other than the top-left corner. I think there's something about the min- properties that makes this work but I'm not sure.

Community
  • 1
  • 1
inthenameofmusik
  • 617
  • 1
  • 4
  • 16
  • 1
    The `transform` in conjunction with the `left` property are a way to force an element of variable width to be centered. First, you go 50% from the left of the container to get to the center of the container, then you go 50% back (negative X) where that 50% represents 50% of the video element's width. Normally, `margin: auto` would center an element, but that element needs to be a fixed width. This strategy allows it to work on elements with unknown or changing widths. – jeffjenx May 15 '16 at 00:10

1 Answers1

1

An absolutely positioned element's position in relation to its parent element (which can also be the browser window) is defined by the top or bottom and left or right parameters (default is top: 0; left: 0;). If left is 50%, it means the left border is moved exactly to the horizontal middle of the container. transform: translateX(-50%) moves it back to the left (caused by the minus value) by 50%, but this time by 50% of the element itself. This causes the element to be ecactly centered horizontally. overflow-x: hidden; makes sure the element doesn't overlap its container - overflowing parts will remain invisible.

You could do the same vertically with top 50%; transform: translateY(-50%); overflow-Y: hidden;

Johannes
  • 64,305
  • 18
  • 73
  • 130