Center A Position:fixed Element


Answer :

You basically need to set top and left to 50% to center the left-top corner of the div. You also need to set the margin-top and margin-left to the negative half of the div's height and width to shift the center towards the middle of the div.

Thus, provided a <!DOCTYPE html> (standards mode), this should do:

position: fixed; width: 500px; height: 200px; top: 50%; left: 50%; margin-top: -100px; /* Negative half of height. */ margin-left: -250px; /* Negative half of width. */ 

Or, if you don't care about centering vertically and old browsers such as IE6/7, then you can instead also add left: 0 and right: 0 to the element having a margin-left and margin-right of auto, so that the fixed positioned element having a fixed width knows where its left and right offsets start. In your case thus:

position: fixed; width: 500px; height: 200px; margin: 5% auto; /* Will not center vertically and won't work in IE6/7. */ left: 0; right: 0; 

Again, this works only in IE8+ if you care about IE, and this centers only horizontally not vertically.


I want to make a popup box centered to the screen with dynamic width and height.

Here is a modern approach for horizontally centering an element with a dynamic width - it works in all modern browsers; support can be seen here.

Updated Example

.jqbox_innerhtml {     position: fixed;     left: 50%;     transform: translateX(-50%); } 

For both vertical and horizontal centering you could use the following:

Updated Example

.jqbox_innerhtml {     position: fixed;     left: 50%;     top: 50%;     transform: translate(-50%, -50%); } 

You may wish to add in more vendor prefixed properties too (see the examples).


Or just add left: 0 and right: 0 to your original CSS, which makes it behave similarly to a regular non-fixed element and the usual auto-margin technique works:

.jqbox_innerhtml {   position: fixed;   width:500px;   height:200px;   background-color:#FFF;   padding:10px;   border:5px solid #CCC;   z-index:200;   margin: 5% auto;   left: 0;   right: 0; } 

Note you need to use a valid (X)HTML DOCTYPE for it to behave correctly in IE (which you should of course have anyway..!)


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?