1、首先盒子模型有两种,W3C的标盒模型和IE的怪异盒子模型
2、两者的区别
1)、盒子模型包括margin、padding、content、border,而W3C标准盒子模型的元素宽度width=content的宽度
而IE怪异盒子模型的元素宽度width=content+padding+border
2)、IE的怪异盒子模型元素宽度的定义更能让人理解,W3C也认识到了这一点,所以在css3中添加了一个样式box-sizing,它有两个属性,分别是content-box和border-box
- content-box:指元素的width=content+padding+border
- border-box:指元素的width=content
3、盒子模型中使用margin:0 auto;需注意的地方
1)、使用margin: 0 auto;水平居中盒子必须有width,要有明确width
2)、只有标准流下的盒子才能使用margin:0 auto;
当一个盒子浮动了,固定定位,绝对定位,margin:0 auto; 不能用了
3)、margin:0 auto;是居中盒子,而不是居中文本,文字水平居中使用text-align: center;
注意:margin:0 auto;失效的原因
- 要给居中的元素一个宽度,否则无效。
- 该元素一定不能浮动或绝对定位,否则无效。
- 在HTML中使用<center></center>标签,需考虑好整体构架,否者全部元素都会居中的。
- 有时需要给父级元素添加text-align: center;
- 有时可能涉及到 <!DOCTYPE>类型相关定义。
4、顺便说一下web开发中让盒子居中的办法
- margin固定宽高居中;
- 负margin居中;
- #container {
position: relative;
width: 600px;
height: 500px;
border: 1px solid #000;
margin: auto;
}
#box {
position: absolute;
width: 200px;
height: 200px;
left: 50%;
top: 50%;
margin: -100px -100px;注意-100=width/2
background-color: #0ff;
} - 绝对定位居中;
- #container {
position: relative;
width: 600px;
height: 500px;
border: 1px solid #000;
margin: auto;
}
#box {
position: absolute;
width: 200px;
height: 200px;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: #0ff;
} - flex居中;
- transform居中;
-
#container { position: relative; width: 600px; height: 600px; border: 1px solid #000; margin: auto; } #box { position: relative; top: 50%; left: 50%; width: 200px; height: 200px; transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); background-color: #0ff; }
- 不确定宽高居中(绝对定位百分数);
-
这种不确定宽高的居中,较为灵活。只需要保证left和right的百分数一样就可以实现水平居中,保证top和bottom的百分数一样就可以实现垂直居中。
CSS:#container {
position: relative;
width: 600px;
height: 500px;
border: 1px solid #000;
margin: auto;
}
#box {
position: absolute;
left: 30%;
right: 30%;
top: 25%;
bottom: 25%;
background-color: #0ff;
}