Pages

Thursday, September 30, 2010

Essential Box Model In CSS


The box model is one of the cornerstones of CSS and dictates how elements are displayed and, to a certain extent, how they interact with each other. Every element on the page is considered to be a rectangular box made up of the element’s content, padding, border, and margin. 



Padding is applied around the content area. If we add a background to an element, it will be applied to the area formed by the content and padding. As such, padding is often used to create a gutter around content so that it does not appear flush to the side of the background.

Adding a border applies a line to the outside of the padded area. These lines come in various styles such as solid, dashed, or dotted. Outside the border is a margin. Margins are transparent and cannot be seen. They are generally used to control the spacing between elements.


Padding, borders, and margins are optional and default to zero. However, many elements will be given margins and padding by the user-agent stylesheet. We can override these browser styles by setting the element’s margin or padding back to zero. We can do this on a case-by-case basis or for every element by using the universal selector:

* {
margin: 0;
padding: 0;
   }

In CSS, width and height refer to the width and height of the content area. Adding padding, borders, and margins will not affect the size of the content area but will increase the overall size of an element’s box. If we wanted a box with a 10-pixel margin and a 5- pixel padding on each side to be 100 pixels wide, we would need to set the width of the content to be 70 pixels.

#myBox

 {
margin: 10px;
padding: 5px;
width: 70px;
}
  


Padding, borders, and margins can be applied to all sides of an element or individual sides. Margins can also be given a negative value and can be used in a variety of techniques.

A box can contain any number of other boxes, creating a hierarchy of boxes that corresponds to the nesting of page elements. The browser window serves as the root element for this hierarchy.

There are two basic types of boxes, block and inline. Block boxes are generated by elements such as P, DIV or TABLE. Inline boxes are generated by tags such as B, I or SPAN and actual content like text and images.

The box type may also be set using the display property. Setting a value of block on an inline element, for example, will cause it to be treated as a block element. Note that if we set the display to none, no box is created. The browser acts as if the element did not exist. Likewise, any nested elements are ignored as well, even if they specifically declare some other display value.
 

No comments:

Post a Comment