Each element in an HTML page defines a rectangular region the browser uses to place the element in the browser window. CSS has a collection of properties for formatting the rectangle around each element. Together these make up what is called the CSS box model.
The following diagram shows the properties of the box model and how they relate to each other:
The innermost box holds the HTML element's content. Between the box contents and the element border lies the padding. Padding size can be set on all four sides of the content. It inherits its color from the background-color property of the content. The margin lies outside the border and gets its color from the parent element.
The most effective way to understand all this is to practice with it, which we begin without delay.
div#box1
style
already in the style sheet:
margin: 40px; padding: 40px; border: 10px solid #000; background-color: #F0F;Reload the page and note how it looks.
div#box2
(put it directly below
the div#box1
style) and add these declarations:
margin: 40px; padding: 40px; border: 10px dotted #000; background-color: #FF0;Again reload the page and observe the changes.
div
element (between the
h1
and hr
styles) with the following rules in
in the declaration block:
width: 500px; height: 200px; background-color: #F70;Reload the page and note how it looks.
div#box2
with the following
rules:
margin: 50px; padding: 50px; border: 10px solid #000;Reload and note the changes.
p
style that will set the width of the corresponding
p
and hr
elements:
.line1 { width: 500px; } .line2 { width: 720px; }Since paragraphs are already set to
text-align: center;
,
setting the width will move text to the center of each hr
element. Again reload the page and note how it looks. If all went well it
should look something like
this.