htmlcss
<div class="father"> <div class="child"></div> </div>
常规流块盒的总宽度,等于其包含块的宽度,也就是其父元素的内容区域html
不设置width,width的默认值为auto,表示吸取掉块盒的剩余空间spa
css3d
.father { height: 200px; border: 5px solid red; padding: 30px; background: lightblue; } .father .child { border: 5px solid red; height: 100px; background: lightcoral; /* 不设置width等同于width为auto */ /* width: auto; */ }
显示效果code
此时child块盒的总宽度为1354px,减去左右border的10px,还剩余1344px,所以width的具体值为1344pxhtm
child的包含块的宽度,也就是father的content部分,也为1354pxblog
margin的默认值为0,值为auto也是吸取掉剩余空间的意思class
但若是给块盒同时设置了width和margin,width的优先级更高im
若设置了width,且width border padding margin计算事后 仍然有剩余空间 因为块盒总宽度须要等于其包含块的宽度 因此该剩余空间默认状况下会被margin-right所有吸取margin
css
.father { height: 200px; border: 5px solid red; padding: 30px; background: lightblue; } .father .child { border: 5px solid red; height: 100px; background: lightcoral; /* 设置width为100px */ width: 100px; }
若设置margin-left:auto; 就表示剩余空间全被margin-left吸取 块盒就排列到包含块的最右边了
css
.father .child { border: 5px solid red; height: 100px; background: lightcoral; /* 不设置width等同于width为auto */ width: 100px; /* 设置margin-left为auto,吸取剩余空间 */ margin-left: auto; }
因此咱们常用的常规流块盒width固定,设置margin: auto; 就表示左右margin平均吸取掉剩余空间 所以就能实现水平居中了
css
.father .child { border: 5px solid red; height: 100px; background: lightcoral; /* 不设置width等同于width为auto */ width: 100px; /* 设置margin左右都为auto,两边平均吸取剩余空间 */ margin: auto; }
height: auto 适应内容的宽度
margin: auto 表示0