简体   繁体   中英

How to align horizontally and vertically to a fixed positioned div?

<div id="someid">some text here</div>

css...

#someid{position: fixed; width: 500px; height: 30px;}

I want to position absolutely center to horizontal and vertical to window?

While your position is fixed you cannot position the div relatively. You must calculate the top and left values by javascript. You can center its position horizontally by writing this:

width: #SOMEWIDTH#px;
margin: 0 auto;

To make the margin position the div at the center the width attribute MUST be set. Auto margining does not affect vertical postiion.

#someid{
position: 
fixed; 
width: 500px; 
height: 30px; 
right:50%; 
margin-right:-250px;
}

The negative margin is to fix the offset that occurs when the browser will consider the div's right side to be 50% from the right of the browser window.

To center it vertically, you may want to try the same thing (no guarantees here though as I haven't done this before) with its vertical position.

For example:

top:50%;
margin-top:-15px;

Edit A little more thorough explanation: When #someid is placed 50% from the right it is positioned so that it is 50% of its parent's total width away from the parent's right border. This however, doesn't measure from the center of #someid to the right border of its parent element, it measures from the right side of #someid to the right side of its parent element. This of course, doesn't quite center #someid, it's still offset by half of its width.

This is why we use a negative margin to offset it. The negative margin needs to be half of #someid's width to make up for the offset to the left that occures when we place it by it's right side 50% from the right of its parent element.

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