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

以下是完整的一套:

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

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


当前回答

如果你的div有一个已知的宽度和高度,那么你基本上需要将top和left设置为50%,以使div的左上角居中。你还需要将margin-top和margin-left设置为div高度和宽度的负一半,以将中心移向div的中间。

position: fixed;
width: 500px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px; /* Negative half of height. */
margin-left: -250px; /* Negative half of width. */

或者,如果你的div有一个动态的/未定义的宽度和/或高度,那么不是边距,而是将变换设置为div的相对宽度和高度的负一半。

position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

或者,如果你的div至少有一个固定的宽度,你不关心垂直居中和老式浏览器(如IE6/7),那么你也可以添加left: 0和right: 0到具有margin-left和margin-right为auto的元素,这样具有固定宽度的固定定位元素就知道它的左右偏移量从哪里开始。在你的情况下:

position: fixed;
width: 500px;
margin: 5% auto; /* Will not center vertically and won't work in IE6/7. */
left: 0;
right: 0;

同样,如果你关心IE的话,这个功能只能在IE8+中工作,而且只能在水平方向上,而不是垂直方向上。

其他回答

你基本上可以将它包装到另一个div中,并将其位置设置为fixed。

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

添加一个这样的容器:

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的宽度。

我想让一个弹出框的中心与动态宽度和高度的屏幕。

这是一个现代的方法,水平居中一个动态宽度的元素-它在所有现代浏览器;支持可以在这里看到。

更新的例子

.jqbox_innerhtml {
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
}

对于垂直和水平居中,你可以使用以下方法:

更新的例子

.jqbox_innerhtml {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

您可能还希望添加更多的供应商前缀属性(参见示例)。

left: 0;
right: 0;

在IE7下无法工作。

更改为

left:auto;
right:auto;

开始工作,但在其他浏览器停止工作! 下面在IE7中使用这种方法

if ($.browser.msie && parseInt($.browser.version, 10) <= 7) {                                
  strAlertWrapper.css({position:'fixed', bottom:'0', height:'auto', left:'auto', right:'auto'});
}

遇到这个问题,所以我得出结论,使用(隐形的)容器是最好的选择(基于@Romulus Urakagi Ts’ai的回答)。用flexbox制作:

.zoom-alert {
  position: fixed;
  justify-content: center;
  display: flex;
  bottom: 24px;
  right: 0;
  left: 0;
  z-index: 100000;
  width: 100%;

  &__alert {
    flex: 0 0 500px;
    padding: 24px;
    background-color: rgba(212, 193, 105, 0.9);
    border: 1px solid rgb(80, 87, 23);
    border-radius: 10px;
  }
}

(语法是SCSS,但可以很容易地修改为纯CSS)