CSS响应水平定心

CSS响应水平定心,css,centering,Css,Centering,我试着将每种屏幕大小的图像(徽标)水平居中,这样做 #container {position:relative width:100%; height:100%;} #logo {position:absolute; top:0; left:50% width:500px; height:100px;} 它不起作用了。我是否需要为容器使用像素宽度 #logo {margin-right:auto; margin-left:auto; width:500px; height:100px;

我试着将每种屏幕大小的图像(徽标)水平居中,这样做

#container {position:relative width:100%; height:100%;}    
#logo {position:absolute; top:0; left:50% width:500px; height:100px;}
它不起作用了。我是否需要为容器使用像素宽度

 #logo {margin-right:auto; margin-left:auto; width:500px; height:100px;}
这是通过告诉图像自动确定固定大小容器左右两侧的空间来居中图像的标准方法


还有一个。

我想这取决于你如何定义“响应”,但如果你指的是响应,即内容调整大小以适应视口的宽度,那么所有其他答案都不符合这一标准,因为它们依赖于固定的像素宽度。例如,如果视图端口小于500px,会发生什么情况

一个类似的概念将适用于百分比宽度,并且实际上是响应的,因为你居中的东西也将是灵活的:

#container { width:100%; height:100%; position:fixed; left:0; right:0; z-index:100;}
#logo { position:fixed; width:80%; z-index:101; left:50%; margin: 10% auto auto -40%;}
如果您不希望“logo”元素变大(在大屏幕上),可以添加
max width:600px
来限制它,但您需要添加一些媒体查询,以使其在大屏幕上正确居中

#container { width:100%; height:100%; position:fixed; left:0; right:0; z-index:100;}
#logo { position:fixed; width:80%; z-index:101; left:50%; margin: 10% auto auto -40%;}