Code Talk #024: 024 CSS Box Model - Recap
September 07, 2021
The Box Model
Understanding the CSS box model is crucial to achieving desired layouts and stylings throughout your application. The CSS box model represents the anatomy of a DOM element, which is a fundamental building block of a website's content.
Each DOM element, whether a <h1>, <div>, etc. is comprise of four parts, starting from the innermost: Content, Padding, Border, and Margin. Each has a role in how the element is positioned and displayed relative to others around it. The analogy I like to use is that of an art gallery wall. Margin is the space between paintings, Border is the frame, Padding is the inset, and Content is the picture itself. When applying width and height CSS attributes, always remember that they apply only to the Content area! If your element has padding, margin and/or border applied, those values will be added to its overall dimensions by default.
One of the first rules of programming is Don't Repeat Yourself. This is especially true in CSS, where it is often egregiously ignored. If you find yourself constantly rewriting the same sets of attributes (e.g. display: flex or color: blue) or if the stylings for an element are becoming unmanageably long, it is a sign you are not using CSS classes effectively. The idea is very simple. Instead of duplicating code for stylings that are common across multiple elements, write a single class that only contains that set of attributes. For example, instead of giving each individual header element a text-align: center attribute, create a class called 'text-center' which sets the text-align atribute to 'center'. Now just add that class to the elements in question. Elements can have any number of classes, so this pattern can be repeated for any set of attributes needed.
CSS is applied in a strictly hierarchical way, with the most specific selector overriding more general ones. The most specific selector is an id (denoted by '#'). Classes (denoted by '.') are the next specific selector type, and element selectors (denoted by the name of the element, such as 'span') are even less specific. There is also the universal selector (denoted by *) which is of course the most general. When the CSS parser is trying to determine which stylings to apply to an element, it first looks at their specificity. In short, the most specific one wins. If there is still a conflict (such as an element which has two classes that assign to the same attribute a different value), then whichever CSS selector was written first gets overridden by the second.