css里不设置width,如何把一个 div 左右居中?

不设置宽度可以把一个div居中吗?

阅读 13.8k
5 个回答
position:absolute; left:10%; right:10%;

使用css3的display:box可以做到。

.box{
display:-webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-pack: center;
display: -o-box;
-o-box-orient: horizontal;
-o-box-pack: center;
display: -ms-box;
-ms-box-orient: horizontal;
-ms-box-pack: center;
display: box;
box-orient: horizontal;
box-pack: center;
}

可参考六种实现元素水平居中

text-align:center;或者margin: 0 auto;

margin-left: auto; margin-right: auto;
需要父容器text-align:center;

你可以试一下这个

.box {
  display: table;
  margin: auto;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题