css - 如何使div在固定位置水平居中?

标签 css html center

<分区>

我想让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不是水平居中的,有什么办法可以做到这一点? 提前致谢。

最佳答案

试试这个

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

JS Fiddle Example

这里需要注意的一点是,margin-left的负值恰好是width的一半,并设置left的50% body

关于css - 如何使div在固定位置水平居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16058823/

相关文章:

css - 如何使用默认选定元素创建 css 'nav'

css - webkit 改造 CSS 并溢出

css - 使用边框调整 html 元素的大小

html - 居中列表项

html - 如何使 <img> 在 div 中居中?

jquery - 使用 .wrapAll child 的宽度被忽略

css - Styled-components 多个伪元素

python - 如何在 jupyter notebook 中将 python 字符串显示为 HTML

css - 设置相同类别的div的颜色?

html - 无法使用文本对齐将文本居中 :center