简体   繁体   中英

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

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> 

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> 

;

If you need to support older browsers you shall use Javascript to make sure it will work since all CSS solution require hard-coding values.

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';

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

I wanted to place an answer with modified left property, but I already see them, so here's some other attempt with position:static freeing inner div from its parent

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

It just doesn't force you to stick with 160%.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM