CSS3 tidbits: background-size and box-sizing

A couple little CSS lessons I learned recently and wanted to pass on…

background-size

I learned about this property a couple of months ago, in a local WordPress meetup. As the name implies, this is used to set the size of background images, as a value or a percentage of the element’s dimensions—and you can set the background height and width separately. There are also a couple of keywords (“contain” and “cover”) to do a couple of extra tricks with the image.

It’s a neat little property that so far I haven’t used myself; but in the example given, the Ridge Meadows Recycling Society, it looks very good. A couple points that were brought up:

  • Apparently, if you’re applying background-size to the entire page, it has to be set for <html>, not <body>. I’m not really sure why that is, though.
  • If you’re using the cover or contain keywords, you need to make sure your background image is at least as big as your element; otherwise it’ll stretch, and obviously not look as good.
  • Not CSS-related, but one of the presenters mentioned working on WordPress templates through text editors + FTP, not through the admin dashboard. That had honestly never occurred to me before, but it makes sense: in the dashboard you can’t roll back your changes since there are no backups, and if you mess up it could take down the whole site (and then you’d have to fix it via FTP anyway).

box-sizing

I needed to set a form field’s width to be exactly as wide as its surrounding div, even counting padding and border, and since I wanted to make the theme responsive I couldn’t set fixed width values. The answer is the box-sizing property. Set its value to “content-box”, and it will draw the element as you’d expect, with the padding and border adding to its width. Set it to “border-box”, and the padding and border will be drawn inside the border box, thus allowing for a snug fit if you write a rule like so:

#sidebar .searchform .s {
  display:block;
  box-sizing:border-box;
  width:100%;
}

box-sizing is supported by most browsers nowadays except Firefox. Not to worry, there are vendor-specific rules you can use (-moz-box-sizing, etc…)