CSS 响应式水平居中
我试图将每个屏幕尺寸的图像(徽标)水平居中,执行类似的操作
#container {position:relative width:100%; height:100%;}
#logo {position:absolute; top:0; left:50% width:500px; height:100px;}
,但它不起作用。我是否必须使用以像素为单位的容器宽度?
I was trying to horizontally center an image (logo) for every screen size doing something like this
#container {position:relative width:100%; height:100%;}
#logo {position:absolute; top:0; left:50% width:500px; height:100px;}
and it's not working. Do I maybe have to use a width for container in pixels?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是通过告诉图像自动确定固定大小容器左侧和右侧的空间来使图像居中的标准方法。
还有一个示例。
This is the standard way of centering an image by telling it to automatically determine the space on both the left and right of a fixed size container.
And an example.
我想这取决于您如何定义“响应式”,但如果您的意思是响应式是指内容调整大小以适应视口的宽度,那么所有其他答案都不符合此标准,因为它们依赖于固定的像素宽度。例如,如果视口小于 500px 会发生什么?
类似的概念将适用于百分比宽度,并且实际上是响应式的,因为您居中的东西也将是灵活的:
如果您不希望“徽标”元素变大(在大屏幕上),您可以添加
max-width:600px;
来限制它,但您需要添加一些媒体查询以使其在大屏幕上正确居中。I guess it depends on how you define "responsive", but if you mean responsive in the sense that content resizes to accomodate the width of the viewport, then all of the other answers don't meet this criteria since they rely on fixed pixel widths. For example, what happens if the view port is less than 500px?
A similar concept will work with percent widths, and actually be responsive, in that the thing you're centering will be flexible too:
If you don't want the "logo" element to get to big (on huge screens), you can add
max-width:600px;
to limit it, but you'd need to add some media-queries to keep it properly centered on large screens.