You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS中border与border-width属性的区别及两类样式代码差异

Hey there! Let's break down the difference between CSS's border shorthand property and the border-width longhand property, plus clear up what's happening with those two code snippets.

Core Differences Between border and border-width

  • border-width: This is a single-purpose longhand property that only controls the width of an element's border. It has no effect on the border's style (like solid, dashed) or color—those require separate border-style and border-color declarations. By default, border-style is set to none, so even if you set border-width: 5px;, you won't see a border unless you explicitly define a style (since a "no-style" border is invisible, no matter how wide it is).
  • border: This is a shorthand property that lets you set border width, style, and color all in one line. It acts as a shortcut for setting border-width, border-style, and border-color simultaneously. If you omit any value, CSS uses the default value for that corresponding property.

The Difference Between border: 5px; and border-width: 5px;

Let's break each down:

border-width: 5px;

  • This line only sets the border width to 5px. The border-style remains its default value (none), and border-color defaults to the element's text color (currentColor). Since there's no border style defined, the border won't render on the page—you can't see a border that has no style, even if it has width.

border: 5px;

  • When you pass only one value to the border shorthand, CSS interprets it as setting border-width: 5px;—but leaves border-style as none and border-color as currentColor, just like the longhand version. So the end result is identical to border-width: 5px;: no visible border.
  • Critical note: The border shorthand requires at least a border-style value to render a visible border. That's because border-style defaults to none, so without specifying a style (like solid, dashed), your border will never show up. For example, border: 5px solid; (uses default text color) or border: 5px solid blue; will render a visible border correctly.

Example Code to Illustrate

/* Neither of these will show a border */
.box-1 {
  border-width: 5px;
}
.box-2 {
  border: 5px;
}

/* This will show a 5px solid border (color matches element's text) */
.box-3 {
  border: 5px solid;
}

/* This will show a 5px solid blue border */
.box-4 {
  border: 5px solid blue;
}

内容的提问来源于stack exchange,提问作者javapedia.net

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:25:53