CSS3 Fundamentals #13 The Box Model
Before we get into the topics of borders, padding, and margins – I need you to visualize something for me. No, this isn’t a throwback to EST; rather just a way for you to picture all of the “stuff” that goes around your elements. Each and every element in HTML has each of these components, and they may vary in size from nonexistent to larger than the element itself.
I’ve taken the requisite 4 minutes to draw you a somewhat accurate diagram of this model:
When you’re attributing values to each of these in CSS, it’s a tremendous help to think of things in terms of this box. With multiple elements on your page, you’ll find that when things start bumping up against each other, you’ll need to have a good grasp on all of these. Otherwise, things will get very confusing, very quickly.
We’ll be dealing with each of the above in much greater detail in later tutorials, but for the moment, here’s the nickel tour:
The content is your element. Any size properties you give your element will make the size of the “content” section of the box. For instance, if you give your element a height of 150px, and a width of 250px, the content dimensions will be 150px x 250px. All of the additional box elements are added on top of this figure.
Padding clears an area for the content within your element, and will assume the background color given to your element. As viewed, if a padding of 10px was added to our element, the total size would appear to be 160px x 260px; but the content within would only stretch to the original dimensions. Think of it as sort of an invisible wall that keeps retrains the content.
The border is the area that extends beyond the padding, and may assume its own unique color independent from the content (and padding). You may also attribute several different properties to the border that are not available to the padding and margin.
The margin is kind of like, and I know it’s a new term, but the padding for the border. It too is not visible, but creates a barrier that another element cannot encroach upon.
Still not entirely clear? Try on this hat: If you think in terms of a framed picture, typically you have the photo, a matte, and a frame. The picture would be the content, the padding would be the matte, and the border would be the frame. But it’s all still seen as a “picture” on a wall. The “margin” would be the space between it, and another picture.
We’ve included a sample file, so if you’re curious, take a look and familiarize yourself with how all of these will appear in your CSS. Now that you’ve seen a visual representation, it will be much easier to wrap your head around. (For once, you’ve just learned a lot more than you probably realize. Nice.)