Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a position:fixed element

I would like to make a position: fixed; popup box centered to the screen with a dynamic width and height. I used margin: 5% auto; for this. Without position: fixed; it centers fine horizontally, but not vertically. After adding position: fixed;, it's even not centering horizontally.

Here's the complete set:

.jqbox_innerhtml {      position: fixed;      width: 500px;      height: 200px;      margin: 5% auto;      padding: 10px;      border: 5px solid #ccc;      background-color: #fff;  }
<div class="jqbox_innerhtml">      This should be inside a horizontally      and vertically centered box.  </div>

How do I center this box in screen with CSS?

like image 794
saturngod Avatar asked Jan 05 '10 12:01

saturngod


People also ask

How can you horizontally center a fixed sized element through CSS?

Add CSS. Set the top and left properties to 50% to center the left-top corner of the <div>. Set the margin-top and margin-left properties to the negative half of the height and width of the <div>.

How do you center an element using position in CSS?

To just center the text inside an element, use text-align: center; This text is centered.


1 Answers

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.

like image 85
BalusC Avatar answered Nov 26 '22 22:11

BalusC