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

以下是完整的一套:

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

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


当前回答

遇到这个问题,所以我得出结论,使用(隐形的)容器是最好的选择(基于@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)

其他回答

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

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

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

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

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

width: calc(100% - 200px);

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

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中使用边缘时,在居中元素内部

或者只是在原始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中正确运行(当然,无论如何您都应该有..!)

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

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