开发者

How many and which values can/should be unitless in CSS

I know two

is there any other?


The currently selected answer is out-of-date, and also misses a few of the ones in the CSS2 spec linked. As I needed a more up-to-date answer, here's a brief summary of what I've found.

Note that this is a list of which properties can be unitless, but not always necessarily should be. Also note obviously that any property which can accept a 'length' value can therefore accept the unitless value of 0.

This lists all CSS3 properties that accept numeric values ([i]nteger or [f]loat):

  • animation-iteration-count (i)
  • border-image-slice (f)
  • border-image-width (f)
  • column-count (i)
  • counter-increment (i)
  • counter-reset (i)
  • flex (i)
  • flex-grow (i)
  • flex-shrink (i)
  • font-size-adjust (f)
  • font-weight (i)
  • line-height (f)
  • nav-index (i)
  • opacity (f)
  • order (i)
  • orphans (i)
  • tab-size (i)
  • widows (i)
  • z-index (i)

In addition to this list, the CSS2 specification also exclusively includes:

  • pitch-range (f)
  • richness (f)
  • speech-rate (f)
  • stress (f)
  • volume (f)

And besides these, there are technically a few obscure ones (related to SVGs):

  • flood-opacity (f)
  • mask-box-outset / mask-border-outset (f)
  • mask-box-width / mask-border-width (f)
  • shape-image-threshold (f)

And, FTW, this seems to be a good reference of all properties that ever existed.


I don't really have an answer for your question, but I just wanted to say that I don't think you should ever leave off the units unless you're specifying a value of 0. It's easier to read and there's no guesswork (for both the browser and someone else who may be reading your CSS).

EDIT: Pulled this from a forum. They are the CSS properties that accept integer values for CSS 2.1 specifications:

  • z-index
  • font-weight
  • line-height
  • counter-reset
  • counter-increment
  • volume
  • stress
  • pitch-range
  • richness


Every numerical value other than 0 should have a unit.

margin:0; //Good
margin:15; //Bad.  Do you want px, em, %, etc?


I am pretty sure I have had instances where leaving the value type off lead to display problems in other browsers. This is because they default to different types.
0 is 0 in any type.
Where 5px (pixels) can be a lot different then 5em (Width of the Current Fonts capital letter M).
As a best practice I say always use them. It's only a few more bytes of bandwidth.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜