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

以下是完整的一套:

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

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


当前回答

添加:

left: calc(-50vw + 50%);
right: calc(-50vw + 50%);
margin-left: auto;
margin-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)

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'});
}

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

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

中心定位元件 (这是我所知道的最简单最好的方法)

position:fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%));

用于水平和垂直居中(如果高度与宽度相同)

position:fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

这两种方法都不会限制居中元素的宽度小于视口宽度,当在flexbox中使用边缘时,在居中元素内部

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

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

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