简体   繁体   中英

Keep absolutely positioned div centered in relation to container not screen

So I have an absolute positioned div that is centered to screen size from the left and the top .

Update: See the demo here http://codepen.io/anon/pen/pJmdJo

.middle {
  top: 50%;
  left: 50%;
  position: absolute;
  transform: translate(-50%, -50%);
  transform-style: preserve-3d;
}

在此输入图像描述

So for example the user is browsing the page with a small sized phone on landscape mode. (screen height shrinks)

在此输入图像描述

The div overlaps as expected and that's not we wanted. This is the result I'm looking for :

在此输入图像描述

div 's height should stop getting smaller than our header 's height. The sticky footer should also stop exceeding the limit.

Note: The body's min-height doesn't exist yet. I believe that's something that should be added. The header is not really a header, it's just the top section of my page, which is a logo and the title of site.

The rest of my code related to other tags, if it matters:

 html, body { height: 100%; width: 100%; overflow: auto; } .wrapper { width: 100%; height: 100%; position: relative; overflow: hidden; } .header { margin-top: 20px; } .middle { top: 50%; left: 50%; position: absolute; transform: translate(-50%, -50%); transform-style: preserve-3d; } .footer { position: absolute; bottom: 0; width: 100%; height: 50px; } 
 <body> <div class="wrapper"> <div class="logo"></div> <div class="header">Welcome</div> <div class="middle">Description</div> <div class="footer"></div> </div> </body> 

Based on your images, you have the centered div absolutely positioned in relation to the entire containing block. So it's always going to center in relation to that container.

If you want to keep the centered div within the light gray area, you then need to assign a position: relative to that section, and then make the centered div a child element of the light gray element. Then, the offsets of the absolute positioning will be in relation to the light gray box.


UPDATE (based on comments and revised question)

It seems the problem you are having is caused primarily by combining both fixed heights (pixels) and relative heights (percentages). If you use only percentage heights in your div containers, the page will scale smoothly.

Try these adjustments to your CSS:

.logo {
    margin: 10px auto 0;
    background: rgba(0, 0, 0, 0) url("... omitted for demo...") no-repeat scroll 0 0;
    height: 20%; /* changed from 80px; */
    width: 80px;
}

.middle {
  position:relative;
  height: 60%; /* changed from 100% */
  background-color: lightgray;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 20%; /* changed from 50px */

DEMO

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