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

以下是完整的一套:

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

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


当前回答

很简单,试试这个

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

其他回答

或者只是在原始CSS中添加left: 0和right: 0,这使得它的行为类似于常规的非固定元素,并且通常的自动边距技术也起作用:

.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;
}

请注意,您需要使用一个有效的(X)HTML DOCTYPE,以使其在IE中正确运行(当然,无论如何您都应该有..!)

试着用这个方法来处理水平元素的居中不正确。

Width: calc (Width: 100% -其他任何偏离中心的宽度)

例如,如果你的侧导航栏是200px:

width: calc(100% - 200px);

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

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

添加一个这样的容器:

div {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
}

然后把你的盒子放入这个div将做的工作。

编辑:正如评论中提到的,内部内容需要设置为display: inline-block,假设有两个div,比如:

    <div class="outer">
        <div class="inner">
             content goes here
        </div>
    </div>

然后内部的CSS需要是:

    .outer {
        position: fixed;
        text-align: center;
        left: 0;
        right: 0;
    }
    .inner {
        display: inline-block;
    }

加上外部div的left: 0;右:0;text-align: center这将使内部div居中对齐,而不显式地指定内部div的宽度。

这个方法对我来说效果最好:

    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;