如何使具有固定位置的div水平居中?

9

我希望将div水平居中,css代码如下:

<style type="text/css">
#footer{
    position: fixed;
    bottom: 20px;
    background-color: red;
    width:500px;
            margin: auto;/*left:auto; right:auto;*/
}
</style>

以及HTML代码:

<body>
<div id="footer">hello world</div>
</body>

我认为我的CSS代码不需要解释,几乎是不言自明的,但是div在水平方向上没有居中,有没有办法实现这个效果? 提前感谢。

position:fixed和margin:auto;在一起使用效果不佳,我正在为您寻找解决方案。 - Nick N.
4个回答

21

试试这个

#footer{
    position: fixed;
    bottom: 20px;
    background-color: red;
    width:80%;
    margin: 0 0 0 -40%;
    left:50%;
}

JS Fiddle示例

这里需要注意的是,将负的margin-left设置为宽度的一半,并将left设置为主体的50%。


1
你的答案和@gregbenner的答案都使用了这个“技巧”,首先感谢。我也刚刚在谷歌上搜索,发现其他人也是用这种方式,我想知道是否有一种没有“技巧”的方法来做到这一点? - hiway
这实际上是一个不错的解决方案。但它并不完全是他想要做的。这样,页脚将变得响应式,并且不会有其固定宽度为500px。 - Nick N.
嗨@Nick,但我也提到了其中的诀窍。他/她可以轻松地根据自己的喜好更改尺寸。 - Sachin
@Sachin 是的,你说得对。可能没有其他方法,除了使用这样的技巧或容器 DIV。 - Nick N.
我们可以使用 transform: translateX(-50%); 来代替设置 margin-left。这样做的好处是,我们不需要每次都计算一半的值。 - manpreet
显示剩余2条评论

8
这对你来说应该很有效。它通过添加一个容器div来实现。
<style>

#footer-container{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
}

#footer
{
    width:500px;
    margin:0 auto;
    margin-bottom:20px;
    background-color:red;
}
</style>


<div id="footer-container">
      <div id="footer">hello world</div>
</div>

"text-align:center;" 会使文本居中并且IE6能够正常工作。如果您不想居中,但是希望IE6能够正常工作,请在 #footer div 中添加 text-align:left。 - Nick N.

6
在其内部放置另一个具有相对位置、margin:auto的div。将固定的div宽度设置为100%。
否则,您可以使用负边距“技巧”进行修改。
div { 
    position: fixed;
    left: 50%;
    width: 500px;
    margin-left: -250px;
}

4
如果您使用现代浏览器,可以使用flexbox布局模块: http://caniuse.com/#feat=flexbox
Flexbox文档: developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
注意: 由于我的声望限制,无法发布超过两个链接。
JSFiddle
(使用footer标签而不是div#footer,因为它更简单。)
<div id="footer-container">
  <footer>hello world</footer>
<div>

#footer-container {
  bottom: 20px;
  position: fixed;

  display: flex;
  justify-content: center;
  width: 100%;
}

footer {
  width: 500px;

  background-color: red;
}

justify-content: center; 可以使 #footer-container 的子元素居中,对于本例来说就是 footer 元素。

这个解决方案与 Nick N. 的解决方案非常相似,但不需要重置 footer 元素的 text-align 属性,而且这可能是您想要的非“技巧”方式。

被接受的解决方案略有偏差,因为在那种情况下,footer 的宽度是可变的(80%),而不是固定的500px。


对于其他读者,如果父元素是 form 元素,而子元素是 input 元素,请在 input(子元素)元素上使用 flex: 1;,并使用 max-width: 500px; 而不是 width: 500px;。使用 flex: 1; 应该使 input 元素扩展以填充 form 元素的宽度,否则可能无法实现。


2
这个解决方案非常好。应该有一种标记答案为“现代浏览器”的方法,这样当仅支持现代浏览器时,我们就可以将它们排在前面。 - Jonathan Park
这太棒了,谢谢。 - dinuka saminda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接