我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
当前回答
如果元素具有宽度和高度,则此解决方案有效
.包装器{宽度:300px;高度:200px;背景色:番茄;位置:相对;}.内容{宽度:100px;高度:100px;背景色:深蓝色;位置:绝对;顶部:0;右:0;底部:0;左:0;边距:自动;}<div class=“wrapper”><div class=“content”></div></div>
其他回答
在寻找解决方案时,我得到了前面的答案,可以将内容以Matthias Weiler的答案为中心,但使用文本对齐:
#content{
position: absolute;
left: 0;
right: 0;
text-align: center;
}
它与谷歌Chrome和Firefox配合使用。
这对我有用:
<div class="container><p>My text</p></div>
.container{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
可以使用calc()将纵横比为1的元素与位置绝对值居中
在下面的示例中,我使用了一个圆,因为它更容易解释和理解,但相同的概念可以应用于任何具有纵横比的形状:1表示宽度和高度相等。(关于纵横比)
:根目录{--直径:80px;}第二部分{位置:绝对;顶部:计算(50%-var(--直径)/2);右:计算(50%-var(--直径)/2);纵横比:1;width:var(--直径);边界半径:100%;背景:蓝色;}<div/>
解释
只需使用一个新的div包装您的内容并使用display flex,然后使用align-items:center;并调整内容:中心;看看。。。
<div class="firstPageContainer">
<div class="firstPageContainer__center"></div>
</div>
.firstPageContainer{
display: flex;
width: 1000px;
height: 1000px;
justify-content: center;
align-items: center;
background-color: #FF8527;
}
.firstPageContainer__center{
position:absolute;
width: 50px;
height: 50px;
background-color: #3A4147;
}
我想补充一下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>