CSS布局需校准盒模型、文档流与脱离机制;box-sizing: border-box应全局设置,浮动塌陷需clearfix清除,margin穿透可用padding-top或border-top解决,居中须按场景选用margin:auto、text-align或transform。
CSS 布局不是“写完就跑”,而是对盒模型、文档流和脱离机制的持续校准——多数布局问题,根源不在 Flex 或 Grid 写得不对,而在没真正理解 box-sizing、float 塌陷、或 margin 穿透这些基础行为。
标准盒模型(box-sizing: content-box)下,width: 300px; padding: 20px; border: 1px solid 的元素实际占宽是 342px。这在响应式中极易导致溢出或错位。
* { box-sizing: border-box; }input、textarea 等表单控件——它们默认是 content-box,不统一就会出现内边距“吃掉”宽度的问题::before)也受此影响,若用它做装饰性边框,需确认是否要参与尺寸计算当所有子元素都设了 float: left,父容器就“看不见”它们了,高度坍缩为 0 ——这不是浏览器缺陷,而是浮动本意:让文字环绕图像,自然要脱离常规流。
.clearfix::after { content: ""; display: table; clear: both; }overflow: hidden 治标:它会意外裁剪 position: absolute 子元素或阴影(box-shadow)padding 或 border,overflow: hidden 还可能遮住这些视觉层给子 div 设 margin-top: 20px,结果整个父容器被往下顶——这是外边距穿透(margin collapse)的典型表现,发生在父元素没有边框、内边距、内容或清除机制时。
margin-top
是否显示为子元素的值padding-top: 1px(最小干预)border-top: 1px solid transparentoverflow: auto(但注意滚动条副作用)float 治这个病:它会引发新的塌陷问题,属于问题套问题“怎么让盒子居中”这个问题,答案取决于你面对的是什么:
margin: 0 auto(仅对 display: block 且有明确 width 的元素有效)text-align: center 在父容器上,子元素设 display: inline-block
.centered { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }(注意:父容器需 position: relative 或非 static)最常被忽略的一点:Flex/Grid 居中(如 justify-content: center; align-items: center)只作用于其直接子项;如果中间夹了一层未设 display: flex 的包裹 div,居中就断掉了。