概念定义
盒子的尺寸来自两条路径:有人告诉它尺寸,或者它测量自己的内容。min-content 回答“最窄能到多少”——最宽的不可断行元素;max-content 回答“永不换行会多宽”;可用空间通过 fit-content 调和两者。
工作机制
百分比与固定宽度是外在的;flex-basis、网格轨道与表格单元倾向内在。flex 项默认 min-width: auto,无法缩到 min-content 以下——这正是侧栏被撑爆的经典原因,min-width: 0 恢复外在控制。网格 minmax 按轨道混合两者,让内容定下限、布局定上限。
使用场景
一切要在长单词、宽表格、语言膨胀下存活的响应式布局。应使用超长字符串与中日文、德文文本测试;overflow-wrap 与连字符在内容必须让步时与尺寸方案互补。
常见误区
内在尺寸会传播:max-content 子元素能把轨道顶得比容器还宽,溢出出现在远离病因的位置。fit-content 的参数设定期望值,可用空间仍会钳制。调试应画出 min-content 宽度,而不是到处撒 overflow: hidden。
代码示例
/* Grid template areas */
.page-layout {
display: grid;
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 250px;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
gap: 1rem;
}
.page-layout > header { grid-area: header; }
.page-layout > nav { grid-area: nav; }
.page-layout > main { grid-area: main; }
.page-layout > aside { grid-area: aside; }
.page-layout > footer { grid-area: footer; }
/* Auto-fit responsive grid */
.auto-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
}
/* 12-column grid system */
.grid-12 {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 1rem;
}
.grid-12 .col-6 { grid-column: span 6; }
.grid-12 .col-4 { grid-column: span 4; }
.grid-12 .col-3 { grid-column: span 3; }
/* Masonry-like layout */
.masonry {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-auto-rows: 10px;
gap: 1rem;
}
.masonry .item-tall { grid-row: span 30; }
.masonry .item-short { grid-row: span 20; }
/* Responsive grid with media query */
@media (max-width: 768px) {
.page-layout {
grid-template-areas:
"header"
"nav"
"main"
"aside"
"footer";
grid-template-columns: 1fr;
}
}
/* Center content perfectly */
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* Responsive navigation bar */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
padding: 1rem;
}
.navbar .menu {
display: flex;
gap: 1.5rem;
flex-wrap: wrap;
}
/* Holy grail layout */
.layout {
display: flex;
min-height: 100vh;
}
.layout .sidebar {
flex: 0 0 200px;
}
.layout .main {
flex: 1;
display: flex;
flex-direction: column;
}
/* Card grid with wrapping */
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.card-grid .card {
flex: 1 1 300px;
}
/* Sticky footer */
.page {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.page .content {
flex: 1 0 auto;
}
.page .footer {
flex-shrink: 0;
}
/* Equal height columns */
.columns {
display: flex;
align-items: stretch;
gap: 1rem;
}
.columns > * {
flex: 1;
}