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 separateborder-styleandborder-colordeclarations. By default,border-styleis set tonone, so even if you setborder-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 settingborder-width,border-style, andborder-colorsimultaneously. 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-styleremains its default value (none), andborder-colordefaults 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
bordershorthand, CSS interprets it as settingborder-width: 5px;—but leavesborder-styleasnoneandborder-colorascurrentColor, just like the longhand version. So the end result is identical toborder-width: 5px;: no visible border. - Critical note: The
bordershorthand requires at least aborder-stylevalue to render a visible border. That's becauseborder-styledefaults tonone, so without specifying a style (likesolid,dashed), your border will never show up. For example,border: 5px solid;(uses default text color) orborder: 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
相关产品推荐
相关产品推荐

