Today I Learned

Be careful about CSS shorthand properties

It’s always better to set certain property instead of using shorthand unless you exactly know what you’re doing.

Example:

  /*doesn't work*/
  background-repeat: no-repeat
  background-position: center
  background: url('http://someurl.jpg')


  /* works*/
  background-repeat: no-repeat
  background-position: center
  background-image: url('http://someurl.jpg')

  /* also works*/
  background: url('http://someurl.jpg')
  background-repeat: no-repeat
  background-position: center

Why?

background-image sets only image as a background

background property on the other hand sets all of these things:

  • background-attachment
  • background-clip
  • background-color
  • background-image
  • background-origin
  • background-position
  • background-repeat
  • background-size

If you don’t specify them intentionally those would be set to their default or unset value

Codepen: link

This is the same case as:

/* won't work - results in right margin to be 8px */
margin-right: 16px
margin: 8px

/* works */
margin: 8px
margin-right: 16px

What other shorthand properties should you be also careful about?

Those:

image

MDN source