CSS veterans probably know this already but it’s one of those minor things that tripped me up when I was learning CSS.

CSS Shorthand Properties allow us to set multiple CSS properties for an element in a single line. A common example is margin:

/* Writing it out in full. */
p {
  margin-top: 1em;
  margin-right: 1.5em;
  margin-bottom: 1em;
  margin-left: 1.5em;
}


/* Using CSS Shorthand Properties. */
p {
  margin: 1em 1.5em;
}

CSS Shorthand Properties are great because they save space and convey a lot of information on just one line.

The thing to keep in mind though is that CSS Properties have initial default values which are applied when said properties are not explicitly defined in shorthand. For example, when using the border shorthand property I only need specify the border-style; the browser automatically fills in the border-width and border-color with their initial default values (in this case medium and the font color respectively):

div {
  color: blue;
  border: solid; /* border-width is set to medium, border-color is set to blue */
}

The tricky part is when we are using CSS Shorthand in conjunction with CSS’s inheritance. Let’s say you want to style all your website modules a certain way but make slight changes to the login module. In this case, we are changing only the border-style. If we were to use CSS Shorthand on the login module, you’ll be in for a little surprise:

.module {
  margin: 1em;
  padding: 1em;
  background: #ccc;
  display: inline-block;
  border: 10px solid red; /* Default border properties for all modules */
}

.module.login {
  border: dotted; /* Here we are trying to change only the border-style of the login module */
}

See the live example at CodePen. And excuse the gaudy style choices, I’m only using them to make a point.

Woah, what happened to my border-color? And did my border get thinner? The reason is because the CSS Shorthand used for .module.login inserted default values for both border-color and border-width which over-wrote the values specified under .module. In this case, if you only want to over-write the border-style you would have to explicitly specify border-style: dotted;.

So there you have it. Nothing earth shaking but hopefully if you’ve just started on your CSS journey you won’t trip over this little problem.