Search code examples
javascriptcsscentering

centering a div in a container larger than 100%


i need to center a div in the viewport in a container larger then 100%.

assuming it's 160% large, i prepared this fiddle:

https://jsfiddle.net/mz0bbz14/2/

usually i would go for:

  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);

but this works only when its container is 100% large.

it's solved with this css

  position:absolute;
  top:50%;
  text-align: center;
  transform:translate(0,-50%);
  width: 100vw;

but the vw unit doesn't work on older android browsers and i need to support it. I can't use jQuery and i don't know how to center it with pure javascript.

i tried setting .div to half the width of the container, but the text inside the div doesn't visually center.

i can't find a solution. any ideas? thanks


Solution

  • If I understand your problem correctly, you want the red .div centered in the left 100% of the parent container that has a width of 160% of the view port.

    In that case, you need to adjust the left offset to be 50% of 100%/160%, which is 31.25%.

    body,html {
      height: 100%;
    }
    .cont-inner {
      width:160%;
      height: 100%;
      background: hotpink;
      position:relative;
    }
    
    .div {
      position:absolute;
      top:50%;
      left: 31.25%;
      transform:translate(-50%,-50%);
      background:red;
      padding:50px; /* smaller size for demo in snippet window */
    }
    <div class="cont-inner">
      <div class="div">
        asd
      </div>
    </div>