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?
If your div has a known width and height, then you basically need to set
topandleftto50%to center the left-top corner of the div. You also need to set themargin-topandmargin-leftto the negative half of the div’s height and width to shift the center towards the middle of the div.Or, if your div has a dynamic/undefined width and/or height, then instead of the
margin, set thetransformto the negative half of the div’s relative width and height.Or, if your div has at least a fixed width and you don’t really care about centering vertically, then you can instead also add
left: 0andright: 0to the element having amargin-leftandmargin-rightofauto, so that the fixed positioned element having a fixed width knows where its left and right offsets start. In your case thus: