Centering a div in a container exceeding 100%

I need to center the div in the viewport in a container greater than 100%.

assuming it is 160% larger, I prepared this fiddle:

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

usually I would go:

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

but it only works when its container is 100% larger.

he decided with this css

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

but the block vwdoes not work in old browsers for Android, and I need to support it. I cannot use jQuery, and I do not know how to focus it on pure javascript.

I tried setting it .divto half the width of the container, but the text inside the div is not visually centered.

I can not find a solution. any ideas? thanks

+4
4

, , .div 100% 160% .

50% 100%/160%, 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>
Hide result
+4

left.

.

160%,

(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>
Hide result

;

+3

, Javascript, , , CSS .

var parent = document.querySelector('.cont-inner'),
    child = parent.querySelector('div');

child.style.left = ((window.innerWidth / 2) - (child.offsetWidth / 2)) + 'px';
child.style.top = ((window.innerHeight / 2) - (child.offsetHeight / 2)) + 'px';

: https://jsfiddle.net/9syvq2r2/

+1

left, , position:static div

https://jsfiddle.net/mz0bbz14/9/

160%.

+1
source

Source: https://habr.com/ru/post/1627668/


All Articles