Here’s a quick anti-pattern (an anti-pattern is something you want to avoid) that I occasionally catch in our markup and CSS.
I opened some code for a new user management screen we’re working on. This excerpt of the users screen shows an avatar, the user’s name, their email address and a reset password link.
The avatar is in a container, and the user info is in a container.
I wasn’t familiar with the code when I opened it, so I assumed the interior white space came from padding on the container. I wanted to add an “admin” checkbox below the user info on the right, and I expected it to align flush left with the name and email. But that’s not what happened.
The checkbox didn’t line up with the text above it. It turned out that the container didn’t have any padding. The text was in its own nested container with a left margin.
This is one of those cases where “it worked” at the time, but as soon as the design needed to change, it broke. This kind of thing makes change painful because you can’t just pop in an element. You pop in an element, but then you have to dig around to see what the margins are supposed to be, move the margins in the right place, and shuffle styles around until the block looks how it should.
To prevent this, I advise thinking about styles as “rules” and “exceptions.” If an element inside a container has padding or margin assigned to it via a CSS selector, that implementation is telling me that the element is a special case. It’s not following the default flow. For some special reason, it needs different spacing. On the other hand, if no elements inside a container are going to look right without the spacing adjustment, that styling should be a “rule” on the container. It should be a constraint for whatever goes inside that container so the design naturally handles additions and future changes.
It also helps to think: which parts of this design are the “room” and which parts are the “furniture”? You should be able to move furniture around without worrying about the walls and volumes of the space. The CSS should be set up in such a way that your space is a constant and you can easily move elements around as you improvise and improve a design.
Back to my project, a quick refactoring moved padding to the container, and going forward this element will handle anything we put into it. Future designers won’t have to think about the containers.
Try keeping these distinctions in mind the next time you’re styling a layout so that future changes are easier to make.