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

以下是完整的一套:

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

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


当前回答

我就用这样的方法:

.c-dialogbox {
    --width:  56rem;
    --height: 32rem;

    position: fixed;

    width:  var(--width);
    height: var(--height);
    left:   calc( ( 100% - var(--width) ) / 2 );
    right:  calc( ( 100% - var(--width) ) / 2 );
    top:    calc( ( 100% - var(--height) ) / 2 );
    bottom: calc( ( 100% - var(--height) ) / 2 );
}

它为我设置了水平和垂直的对话框中心,我可以使用不同的宽度和高度来适应不同的屏幕分辨率,以使其具有媒体查询的响应性。

如果您仍然需要为不支持CSS自定义属性或calc()的浏览器提供支持,则不可取(请检查caniuse)。

其他回答

我就用这样的方法:

.c-dialogbox {
    --width:  56rem;
    --height: 32rem;

    position: fixed;

    width:  var(--width);
    height: var(--height);
    left:   calc( ( 100% - var(--width) ) / 2 );
    right:  calc( ( 100% - var(--width) ) / 2 );
    top:    calc( ( 100% - var(--height) ) / 2 );
    bottom: calc( ( 100% - var(--height) ) / 2 );
}

它为我设置了水平和垂直的对话框中心,我可以使用不同的宽度和高度来适应不同的屏幕分辨率,以使其具有媒体查询的响应性。

如果您仍然需要为不支持CSS自定义属性或calc()的浏览器提供支持,则不可取(请检查caniuse)。

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

    display: flex;
    justify-content: center;
    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;

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

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

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

如果你的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+中工作,而且只能在水平方向上,而不是垂直方向上。