Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 862
valerio0999 Avatar asked Jan 06 '23 16:01

valerio0999


2 Answers

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>
like image 198
Marc Audet Avatar answered Jan 09 '23 06:01

Marc Audet


You need to change the left property.

It needs to be in the middle of the visible part of the container.

Since it's 160%, it is

(100 / 160) * 0.5 -> 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:100px;
}
<div class="cont-inner">
  <div class="div">
    asd
  </div>
</div>

;

like image 27
vals Avatar answered Jan 09 '23 07:01

vals