我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。

我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。

.center {
  left: 50%;
  bottom: 5px;
}

我怎样才能做到这一点?


当前回答

这对我有用:

<div class="container><p>My text</p></div>

.container{
    position: absolute;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
}

其他回答

我想补充一下bobince的回答:

<body>
    <div style="position: absolute; left: 50%;">
        <div style="position: relative; left: -50%; border: dotted red 1px;">
            I am some centered shrink-to-fit content! <br />
            tum te tum
        </div>
    </div>
</body>

改进:///这使得水平滚动条不会在居中的div中出现大元素。

<body>
    <div style="width:100%; position: absolute; overflow:hidden;">
        <div style="position:fixed; left: 50%;">
            <div style="position: relative; left: -50%; border: dotted red 1px;">
                I am some centered shrink-to-fit content! <br />
                tum te tum
            </div>
        </div>
    </div>
</body>

尽量不要使用CSS的阴暗面。避免使用负值作为边距。我知道有时候你会被迫做一些糟糕的事情,比如左边距:-450px,但你可能会做一些右边距:450px。这只是我的工作方式。

如果元素具有宽度和高度,则此解决方案有效

.包装器{宽度:300px;高度:200px;背景色:番茄;位置:相对;}.内容{宽度:100px;高度:100px;背景色:深蓝色;位置:绝对;顶部:0;右:0;底部:0;左:0;边距:自动;}<div class=“wrapper”><div class=“content”></div></div>

这适用于您希望在容器元素中心具有的绝对定位元素的任意未知宽度:

Demo

<div class="container">
  <div class="box">
    <img src="https://picsum.photos/200/300/?random" alt="">
  </div>
</div>

.container {
  position: relative;
  width: 100%;
}

.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

我知道这个问题已经有了一些答案,但我从来没有找到一个能在几乎所有的类中都适用的解决方案,它也很有意义,而且很优雅,所以这里是我经过调整后的看法:

.容器{位置:相对;}.container.cat链接{位置:绝对;左:50%;顶部:50%;变换:translate3d(-50%,-50%,0);z指数:100;文本转换:大写;/*强制CSS将其视为文本,而不是纹理,这样就不会出现更模糊的错误*/背景色:白色;}.色块{高度:250px;宽度:100%;背景色:绿色;}<div class=“container”><a class=“cat link”href=“”>类别</a><div class=“color block”></div></div>

这是说给我一个顶部:50%,左侧:50%,然后在X/Y轴上变换(创建空间)到-50%的值,在某种意义上“创建镜像空间”。

因此,这会在div的所有四个点上创建一个相等的空间,它始终是一个长方体(有四条边)。

这将:

工作时不必知道父对象的高度/宽度。致力于响应。在X轴或Y轴上工作。或者两者兼而有之,就像我的例子一样。我不能想出一个不起作用的情况。