简体   繁体   中英

Vertically align a Div in the Browser window (-not- within another element)

I have a div which i want vertically aligned to 50% of the height of the browser window at all times.

I don't know what the height of the browser window is going to be at all times, should the user scale this window. If placing it within another element is necessary, great, but as just specified, I have no idea how tall the viewport is going to be at any one time.

I'm not going to be using javascript either.

I have read through the site, i have gone hunting for a solution, but I really want to throw this out there (again) as I have yet to find a solution that does exactly this, either by hook or by crook.

Thanks.

You don't specify if the has a fixed height or not? If so then you can do this with one element, just add the following example CSS:

.centered {
  height: 100px;
  width: 100%;
  background: red;
  position: absolute;
  top: 50%;
  left: 0;
  margin-top: -50px; /* half the height of the element */
}

You could use a number of techniques, depends on how you exactly want to implement it. Some (older) but still relevant reading here .

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