Backgrounds for the Box Model (and why it can be useful)
Backgrounds for the Box Model (and why it can be useful) êŽë š
I had someone write to me the other day that they were trying to visualize the different parts of the box model. They said they would just code up an example themselves, but there is no way to, say, set a background color for just the âpaddingâ area of an element.
What they were talking about is something like this, the box model diagram available in DevTools:
I said, I think you⊠can! actually!
The trick lays in using the background-clip
property in CSS, which allows you to stop the background-image
property at different points in the box model. Hereâs a really basic example of doing that, using the same colors as the model above:
The only one Iâm âfakingâ there is the very outer shape (margin), which is drawn with an outline
. It does match the value of margin
though so itâs basically real!
I was a bit inspired to keep going, making all the values dynamic, so I made this, which labels the section as well.
I put a grid of content around it so that you could see the element push others away like the real box model does.
Is this actually useful ever? Sometimes!
Just the other day Wes Bos posted a really nice button effect and then re-created in HTML and CSS:
There is no real big problem with how Wes did it there, but he did use an extra element as well as pseudo elements to get it done. Hereâs his demo. (wesbos
)
Ana Tudor chimed in (anatudor
) that it could be done without using any extra elements, and guess how? Background clipping!
I took a crack at that, and aside from a bit of an awkward need to set the background-size
, I think I got it working:
This may actually be truly useful sometimes. For example, a CMS that is happy to spit out a <button>
element but doesnât offer inner HTML control of it. If you donât need that anyway and can pull of the effect in CSS entirely, youâre in business.
Because Iâm a glutton for punishment sometimes, I also decided to have a crack at it using border-image
as well, which despite being the lest scrutable CSS property of all time, seems at least conceptually like the correct thing to use. I was able to get it working!
But for whatever reason border-image
is incompatible with border-radius
, so, whatever, that sucks.