在同一个元素上使用高度和边框是好习惯吗?

Is it good practice to use height and border on the same element?

我的一些同学告诉我,同时使用 borderheightwidth 会弄乱盒子的尺寸。

我花了很多时间对此进行研究(看看这是不是真的)但我找不到任何答案。

同时使用这些属性(borderheightwidth)是否是一种好的做法? 这会给我带来什么麻烦吗?

.infobox {
    background-color: white;
    border: 1px solid black;
    float: right;
    height: 125px;
    width: 150px;
}

使用边框完全没问题! 它确实使事情变得有点复杂,因为边框添加到总数 wodth/height,但这可以通过使用 box-sizing: border-box 来解决,这使得填充和边框包含在 width/height 中。我建议您熟悉盒子模型:

(图片来自W3Schools

是的,在一个元素上同时使用 heightborder 属性是完全没问题的。你的同学正在参考 CSS 盒子模型的工作原理,这是你在构建 CSS.

时需要注意的事情

默认框模型是 content-box 其中:

The width and height properties are measured including only the content, but not the padding, border or margin.

框大小调整 (https://developer.mozilla.org/en/docs/Web/CSS/box-sizing)

这意味着在您的示例中 .infobox 的最终高度为 127(高度 + 边框),宽度为 152(宽度 + 边框)。

备选盒子模型是 border-box 其中:

The width and height properties include the padding and border, but not the margin.

框大小调整 (https://developer.mozilla.org/en/docs/Web/CSS/box-sizing)

使用此盒模型会导致 .infobox 最终高度为 125,宽度为 150,因为考虑了边框。

请参阅以下代码段以了解两个框大小选项的演示:

.infobox {
  border: 1px solid black;
  float: left;
  height: 125px;
  width: 150px;
}
.contentBox {
  background-color: red;
}
.borderBox {
  background-color: blue;
  box-sizing: border-box;
}
<div class="contentBox infobox">content-box</div>
<div class="borderBox infobox">border-box</div>