我想做一个职位:固定;弹出框居中与屏幕的动态宽度和高度。我使用保证金:5% auto;对于这个。无位置:固定的;它的水平中心很好,但不是垂直中心。添加position: fixed;后,水平方向甚至没有居中。

以下是完整的一套:

.jqbox_innerhtml { 位置:固定; 宽度:500 px; 身高:200 px; 利润率:5%汽车; 填充:10 px; 边框:5px实体#ccc; background - color: # fff; } < div class = " jqbox_innerhtml”> 这应该在一个水平的 垂直居中的盒子。 < / div >

我如何中心这个框在屏幕与CSS?


当前回答

#modal {
    display: flex;
    justify-content: space-around;
    align-items: center;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}

在它里面可以是任何有差异宽度,高度或没有的元素。 全部居中。

其他回答

很简单,试试这个

position: fixed;
width: 500px;
height: 300px;
top: calc(50% - 150px);
left: calc(50% - 250px);
background-color: red;

添加:

left: calc(-50vw + 50%);
right: calc(-50vw + 50%);
margin-left: auto;
margin-right: auto;

当你不知道你正在居中的东西的大小,而你想让它在所有屏幕尺寸中居中时,这个方法非常有效:

.modal {
  position: fixed;
  width: 90%;
  height: 90%;
  top: 5%;           /* (100 - height) / 2 */
  left: 5%;          /* (100 - width) / 2 */
}

唯一可靠的解决方案是使用表align=center,如下所示:

<table align=center><tr><td>
<div>
...
</div>
</td></tr></table>

我无法相信世界各地的人们浪费这么多愚蠢的时间来解决这样一个基本的问题,如集中一个div. css解决方案并不适用于所有浏览器,jquery解决方案是一个软件计算解决方案,并不是一个其他原因的选择。

我已经浪费了太多的时间来避免使用桌子,但经验告诉我不要再这样做了。使用表格为div居中。在所有浏览器中都有效!再也不用担心了。

我用的方法很简单。例如,我有一个定位:固定的导航条,所以我调整它,在边缘留下一个小空间,像这样。

nav {
right: 1%;
width: 98%;
position: fixed;
margin: auto;
padding: 0;
}

其思想是取宽度的剩余百分比(在本例中为2%)并使用它的一半。