CSS 尺寸
CSS 尺寸属性
Section titled “CSS 尺寸属性”CSS 尺寸属性(width、height、min-width、min-height、max-width、max-height)允许您控制网页上元素的大小。
掌握这些属性并理解不同的单位对于创建结构良好且响应式的布局至关重要。
设置 width 和 height
Section titled “设置 width 和 height”width 和 height 属性显式设置元素的 content box 的尺寸(除非使用 box-sizing: border-box,在这种情况下,它设置包括 padding 和 border 在内的尺寸)。
px(像素): 固定大小单位。适用于不应缩放的元素,但对于响应式设计灵活性较低。%(百分比): 相对于其包含块的宽度或高度。非常适合流体布局。em: 相对于元素自身的font-size(如果元素未设置font-size,则相对于其父元素)。适用于可伸缩组件。rem(根 em): 相对于根元素(<html>)的font-size。非常适合创建全局可伸缩界面。vw(视口宽度): 视口宽度的百分比。10vw表示当前视口宽度的 10%。vh(视口高度): 视口高度的百分比。50vh表示当前视口高度的 50%。vmin/vmax: 视口较小维度(vmin)或较大维度(vmax)的百分比。auto(默认): 浏览器计算宽度/高度。对于块级元素,width: auto通常表示全部可用宽度。对于height,通常表示根据内容调整。
.fixed-box { width: 200px; height: 100px; background-color: lightblue;}
.fluid-box { width: 80%; /* 父元素宽度的 80% */ height: 10rem; /* 根字体大小的 10 倍 */ background-color: lightgreen;}
.viewport-section { width: 100vw; /* 全视口宽度 */ height: 50vh; /* 半视口高度 */ background-color: lightcoral;}控制尺寸限制:min- 和 max-
Section titled “控制尺寸限制:min- 和 max-”min-width、min-height、max-width 和 max-height 为元素的尺寸提供约束。
min-width/min-height:确保元素不会小于指定尺寸,即使其内容较少或width/height设置为较小值也是如此。max-width/max-height:防止元素大于指定尺寸,即使其内容较多或width/height设置为较大值也是如此。
使用 max-width 实现响应式图片:
Section titled “使用 max-width 实现响应式图片:”响应式设计中一个常见且关键的技术是为图片应用 max-width: 100%;。这使得图片可以按比例缩小以适应其容器,同时防止它们超出其自然尺寸。
img { max-width: 100%; /* 需要时缩小 */ height: auto; /* 保持宽高比 */ display: block; /* 可选:移除图片下方的额外空间 */}组合使用 min- 和 max-:
Section titled “组合使用 min- 和 max-:”您可以组合这些属性来创建具有尺寸边界的灵活元素。
.flexible-container { width: 80%; /* 基础宽度 */ min-width: 300px; /* 不小于 300px */ max-width: 800px; /* 不大于 800px */ margin: 0 auto; /* 达到 max-width 时居中容器 */ height: auto; min-height: 100px; background-color: #eee; padding: 1rem;}固有尺寸 (高级)
Section titled “固有尺寸 (高级)”CSS 还提供固有尺寸关键字,如 min-content、max-content 和 fit-content。这些关键字根据元素的内容尺寸来决定大小。
min-content:元素在不溢出的情况下可以达到的最小尺寸(例如,宽度由最长的单词决定)。max-content:基于元素内容的理想尺寸(例如,显示所有内容而不断行所需的宽度)。fit-content(value):使用可用空间,最大不超过max-content,但也不小于min-content或指定的value。
这些在 CSS Grid 等布局系统中非常强大。
.item { width: fit-content(200px); /* 宽度与内容一致,但最大不超过 200px */}所有 CSS 尺寸属性总结
Section titled “所有 CSS 尺寸属性总结”常用 CSS 尺寸属性(::)
Section titled “常用 CSS 尺寸属性(::)”| 属性 | 描述 | 常用值 |
|---|---|---|
| height | 设置元素内容区域的高度。 | auto、length(例如,100px、10em)、%、vh、min-content、max-content、fit-content(...) |
| width | 设置元素内容区域的宽度。 | auto、length(例如,250px、20rem)、%、vw、min-content、max-content、fit-content(...) |
| max-height | 设置元素可以有的最大高度。 | none、length、%、vh、min-content、max-content、fit-content(...) |
| max-width | 设置元素可以有的最大宽度。 | none、length、%、vw、min-content、max-content、fit-content(...) |
| min-height | 设置元素必须有的最小高度。 | auto、length、%、vh、min-content、max-content、fit-content(...) |
| min-width | 设置元素必须有的最小宽度。 | auto、length、%、vw、min-content、max-content、fit-content(...) |
有关单位和属性的详细信息,请参阅 MDN:https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Values_and_Units