如何让一个盒子上下左右居中的问题。

我想到了两种CSS方法实现:

1.

.box{

margin:auto;

position:absolute;

left:0;

right:0;

bottom:0;

top:0;

width:200px;

height:200px;

}

2.

.box{

position:absolute;

left:50%;

right:50%;

width:200px;

height:200px;

margin-left:-100px;

margin-top:-100px;

}

测试后神奇的发现,第二种方法下,盒子值上下居中,不能左右居中,请问是什么问题造成的(页面中没有其他多余的样式,只加了box的样式,加了一个div标签)。

行走的指尖
浏览 3363回答 2
2回答

行走的指尖

啊,我知道问题了,非常感谢大家

脑袋空空空想家

position设置成为absolute以后,margin就会失效了。<!DOCTYPE html><html><head><meta charset="UTF-8"><title>ajax</title><style>.a1{width: 100px;height: 100px;position: absolute;background-color: red;top:0;bottom: 0;left: 0;right: 0; margin: auto;}</style></head><body><div></div></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP