我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
当前回答
绝对中心
HTML格式:
<div class="parent">
<div class="child">
<!-- content -->
</div>
</div>
CSS:
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
演示:http://jsbin.com/rexuk/2/
它在Google Chrome、Firefox和Internet Explorer 8中进行了测试。
其他回答
HTML格式:
<div class="wrapper">
<div class="inner">
content
</div>
</div>
CSS:
.wrapper {
position: relative;
width: 200px;
height: 200px;
background: #ddd;
}
.inner {
position: absolute;
top: 0; bottom: 0;
left: 0; right: 0;
margin: auto;
width: 100px;
height: 100px;
background: #ccc;
}
这里还有更多的例子。
在寻找解决方案时,我得到了前面的答案,可以将内容以Matthias Weiler的答案为中心,但使用文本对齐:
#content{
position: absolute;
left: 0;
right: 0;
text-align: center;
}
它与谷歌Chrome和Firefox配合使用。
我知道这个问题已经有了一些答案,但我从来没有找到一个能在几乎所有的类中都适用的解决方案,它也很有意义,而且很优雅,所以这里是我经过调整后的看法:
.容器{位置:相对;}.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轴上工作。或者两者兼而有之,就像我的例子一样。我不能想出一个不起作用的情况。
这对我有用:
<div class="container><p>My text</p></div>
.container{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
这适用于垂直和水平:
#myContent{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
如果要使父对象成为元素中心,请设置父对象的相对位置:
#parentElement{
position: relative
}
对于垂直居中对齐,请设置元素的高度。感谢劳尔。如果要使父对象成为元素中心,请将父对象的位置设置为相对位置