Phase 0 - Week 2 The CSS Box Model
Friday, May 8, 2015
This week, we spent a lot of time learning about HTML and CSS. We created a website using HTML and then built the style sheet required to transform the HTML to recreate an existing website. In order to successfully complete this task, we needed to have an understanding of many different functions of CSS. In this blog, I will explain the CSS Box Model and how to use it to adjust they way elements are displayed on your website.
Since all HTML elements can be considered as boxes, the CSS Box Model is important to understand because it will help you successfully position and/or shift items on the page to ensure that they display exactly as you intend. There are 4 key components of the CSS Box Model that are represented in the below graphic: the content area, padding (green area), border (black line) and margin (blue area).
Think about this as if you were packing an item in a box to move; you would use padding around the item to protect it. In the CSS Box Model, padding is the spacing between the content area and the border, and it has the same background color as the content area. An example of a situation where padding is important would be if you have text in a bordered box and the text is too close to the border; in this examply, you will need to increase the padding. Since the margin is the spacing between the border and the margin of the boxes surrounding it, you would adjust the margin if you had two bordered boxes where the borders were too close together. Remember, all HTML elements are boxes so if you want two boxes to touch you need to adjust the margins of both items.
The padding, border and margins for every box can be adjusted together or individually. As shown in the graphic above, the padding and margin setting were adjusted together and the border settings for the right and bottom were set individually. If you're anything like me, you will have to stop and try to remember the order of the settings for top, right, bottom and left. Thanks to my pair for the CSS challenge (Daniela) I just think of it like a clock starting out at the top of the hour.
In addition to adjusting the spacing of items using padding and margin, there are a bunch of style changes that can be applied to the border. You can change the thickness color and style (solid, dashed etc) of the border and even give it rounded corners. Try it out for yourself, add border-radius: 10px; to a box and see what happens, change the radius to 50% and you have a circle. Who said you can't fit a square peg in a round hole? They obviously don't know their CSS!
These are just a few things that you can do when you understand the CSS Box Model. For more information and/or practice with the box model, check out www.w3schools.com.