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?
You can basically wrap it into another
div
and set itsposition
tofixed
.Or just add
left: 0
andright: 0
to your original CSS, which makes it behave similarly to a regular non-fixed element and the usual auto-margin technique works:Note you need to use a valid (X)HTML
DOCTYPE
for it to behave correctly in IE (which you should of course have anyway..!)Was not working under IE7.
Changed to
Started working but in the rest browsers it stop working! So used this way for IE7 below
Try using this for horizontal elements that won't center correctly.
width: calc (width: 100% - width whatever else is off centering it)
For example if your side navigation bar is 200px:
The only foolproof solution is to use table align=center as in:
I cannot believe people all over the world wasting these copious amount to silly time to solve such a fundamental problem as centering a div. css solution does not work for all browsers, jquery solution is a software computational solution and is not an option for other reasons.
I have wasted too much time repeatedly to avoid using table, but experience tell me to stop fighting it. Use table for centering div. Works all the time in all browsers! Never worry any more.
You basically need to set
top
andleft
to50%
to center the left-top corner of the div. You also need to set themargin-top
andmargin-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:Or, if you don't care about centering vertically and old browsers such as IE6/7, then you can instead also add
left: 0
andright: 0
to the element having amargin-left
andmargin-right
ofauto
, so that the fixed positioned element having a fixed width knows where its left and right offsets start. In your case thus:Again, this works only in IE8+ if you care about IE, and this centers only horizontally not vertically.