【发布时间】:2015-02-24 04:36:51
【问题描述】:
在使用 CSS 进行样式设置时,我注意到 padding 属性可以轻松实现与 height 属性相同的效果......但是 padding 属性使我的文本保持美观和居中,而 height 属性迫使我添加其他 CSS规则/调整行高。
放弃 height 属性并使用填充来代替元素的高度是“错误”还是违反常用的 CSS 标准?
这会带来什么影响?
【问题讨论】:
标签: css syntax standards styling
在使用 CSS 进行样式设置时,我注意到 padding 属性可以轻松实现与 height 属性相同的效果......但是 padding 属性使我的文本保持美观和居中,而 height 属性迫使我添加其他 CSS规则/调整行高。
放弃 height 属性并使用填充来代替元素的高度是“错误”还是违反常用的 CSS 标准?
这会带来什么影响?
【问题讨论】:
标签: css syntax standards styling
height 和 padding 都在本质上控制元素的高度。我不得不不同意使用填充是错误的,而是取决于具体的用例。
在需要固定容器尺寸时使用高度。
当您不需要固定的容器高度但想要添加空格时使用填充。
对混合方法使用 min-height 和 max-height。
【讨论】:
是的,使用padding来控制元素高度是错误的。
height 控制元素的实际高度(基本上是border-bottom 到border-top 的距离),而padding 控制内容和边框之间的距离。
【讨论】:
您可以使用box-sizing 属性:
默认情况下,元素的宽度和高度计算如下 这个:
- Width + Padding + Border = 元素的实际宽度
- 高度 + 填充 + 边框 = 元素的实际高度
这意味着:元素的边框和内边距被添加到元素的指定宽度/高度。
使用box-sizing 属性将允许您将元素内边距和边框作为其总高度和宽度的一部分。
当您设置box-sizing: border-box; 时,元素的内边距和边框将作为其总宽度和高度的一部分。
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
}
<div class="div1">This div is smaller (width is 300px and height is 100px).</div>
<br>
<div class="div2">This div is bigger (width is also 300px and height is 100px).</div>
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
box-sizing: border-box;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
box-sizing: border-box;
}
<div class="div1">Both divs are the same size now!</div>
<br>
<div class="div2">Hooray!</div>
【讨论】: