我想做一个职位:固定;弹出框居中与屏幕的动态宽度和高度。我使用保证金: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+中工作,而且只能在水平方向上,而不是垂直方向上。

其他回答

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

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

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

width: calc(100% - 200px);

要确定位置,请使用以下命令:

div {
    position: fixed;
    left: 68%;
    transform: translateX(-8%);
}

另一个简单的解决方案是将元素的宽度设置为fit-content,并将左右设置为0px;

width: fit-content;
position: fixed;
left: 0px;
right: 0px;

如果您不知道元素的宽度,这是很有用的。

如果你的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 {
  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的宽度。