CSS Box Model Explained
CSS Box Model - in laymans terms!
The very basis of designing with CSS is learning how the CSS Box Model works.
Now don't be scared it's quite simple really. Repeat after me...
ALL HTML elements are BOXES
... when you have that firmly committed to memory it makes everything else easy. These "Boxes" are invisible, or the specifications call them anonymous, but using some clever CSS trickery I will show you where they are!
Margin, Padding and Borders
Margins, padding and borders are the invisible gift wrap, packing and cardboard, their correct term is properties, that go around the element to create this Box. You do not need to use any of these properties to create your box, but when you do you need to be aware that they will affect its size.
When I said that all elements are in Boxes, I meant it.. here's how a basic element would look if it weren't invisible.
400px line for measurement
20px + 15px + 20px + 290px + 20px + 15px + 20px = 400px
Now to deconstruct the above:
- Gift in The Box
- The white area in the center is the heart of the element, it represents the priceless gift inside the box, I'm sending a 290px wide gift this year.
- The Gift is Fragile!
- The priceless gift inside the box is fragile, so makes sure it's well padded. I chose to give it 20px of light pink padding.
- Choose your Carton wisely....
- The border represents the carton that you pack the gift in, in this instance I chose a 15px thick black carton
- Get out of my space!
- The margin represents the gift wrap. The thicker the wrapper the further away from the next box yours will be. So I have gone for nice violet coloured 20px thick wrap.
- It all adds up.
- So now your whole box is ready to go, but all those components add up. The element itself is 290px wide but with all the rest of the components added it becomes 400px wide, so your invisible box surrounding this whole element is 400px wide.
Who is this present for?
Well it's for you of course! Take it tear it open, play with it and don't forget that whenever you are trying to position your element on a web page that all of the Box Model Properties will affect it's place in life.
A present? - What's the catch?
As if... Well unfortunately there is one and it's a biggie. IE, the browser of choice for the majority of web viewers, gets the Box Model wrong! Now that's a topic unto itself, but there are various ways to get around it and I'll put some references at the bottom of this page for you. However I feel it's important to know what should happen, this should then make it easier to understand the various workarounds.
Updates:
Resources:
- W3C - Technical explanation - CSS1 - the formatting model
- W3C - World Wide Web Consortium - CSS2 Recommendations for Box Model Properties
- RichInStyle CSS2 tutorial - tutorial about the box model
- Box Model Hacks - for IE - listed by CSS discuss
«« To CSS Index »» | CSS Borders - Beauty in Simplicity »»
