我希望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不是水平居中,有没有办法做到这一点? 提前谢谢。
答案 0 :(得分:20)
试试这个
#footer{
position: fixed;
bottom: 20px;
background-color: red;
width:80%;
margin: 0 0 0 -40%;
left:50%;
}
此处需要注意的是,margin-left
的正值为width
的正值为left
并将{{1}}设为身体的50%
答案 1 :(得分: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>
答案 2 :(得分:6)
将另一个div放入其中,相对位置,margin:auto。 给固定的100%宽度。
否则你可以用负边距'技巧'来破解它
div {
position: fixed;
left: 50%;
width: 500px;
margin-left: -250px;
}
答案 3 :(得分:4)
如果您正在使用现代浏览器,则可以使用flexbox布局模块:http://caniuse.com/#feat=flexbox。
Flexbox文档:developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
注意:由于我的代表不能发布两个以上的链接。
(使用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;
&#39;中心&#39; #footer-container
的孩子,在这种情况下只是footer
元素。
这与Nick N。的解决方案非常相似,只是您不必重置页脚上的text-align
属性,而这可能是非&# 39特技&#39;你想要的方式。
接受的解决方案略有偏差,因为在这种情况下页脚的宽度是可变的(80%)而不是500px。
对于其他读者,如果您的父级是form
元素且子级是input
元素,请在flex: 1;
(子)元素上使用input
,并且使用max-width: 500px;
代替width: 500px;
。使用flex: 1;
应该展开input
元素以填充form
元素的宽度,否则它可能不会这样做。