Published at
Updated at
Reading time

This post is part of my Today I learned series in which I share all my learnings regarding web development.

I love smart CSS tricks and today I read "Restricting a (pseudo) element to its parent’s border-box" written by Ana Tudor. And while this article includes all the CSS magic, you may know Ana for it also brought up a tiny CSS detail I wasn't aware of.

Before going into my learning, let's dive into the CSS box-model for a minute. The CSS box-model defines several areas of the elements and how they're laid out. These are the content-box, padding-box, and border-box and you can have a look at these in your developer tools of choice.

box-model in Chrome devtools showing content-box, padding-box, and border-box

It's not only essential to know about the box-model when you want to design a website but also when you want to create advanced CSS backgrounds as Ana describes in her article.

Thanks to the three defined areas in the box-model, you can also apply three different CSS backgrounds to the same element without adding additional markup.

The following CSS...

.someManyGradients {
  // more stuff
    linear-gradient(90deg, #F2BC1B, #B27C00) content-box,
    linear-gradient(#f1f1f1, #ccc) padding-box,
    linear-gradient(-90deg, #8C142A, #5C0000) border-box;

... lets you style single elements with several gradients. 🎉

an element using three different gradients thanks to the box-model

If you want to learn more about this technique, you can also have a look at this article in which I explain a specific element on CSSTricks this in detail.

But what happens when you have elements that overflow (let's say with absolute positioning) and you want to make them fit right into the pretty gradient-element?

Visualization showing that overflow: hidden hides everything outside of the padding-box

It turned out that the flowing element can not going over the red border. The CSS Overflow spec defines this behavior:

This value indicates that the box’s content is clipped to its padding box [...]

I think this is very surprising because I expected that the inner element would cover the red border-box, too.

If you want to learn how to come around this behavior, have a look at Ana's article or if you want to play around with the included example element you can find it on CodePen.

Related Topics

Related Articles