CSS box model and position model

I have written some css to customize my blog this week. Then I realized that I didn’t get a clear understanding of common css attributes like top, left, height and width. Often I mixed them up. I suggest once you get confused about those properties, you'd better take a look at the box model and position model. It will help a lot.

Box model

There’s a box around every css element. It’s all related with property margin, padding, border, width and height. There are two kinds of box. One is inline and the other is block. If the display is inline, width and height will not take effect. Below is an example to show the block style.

.block-style {
    width: 300px;
    height: 300px;
    padding: 20px;
    margin: 40px;
    border: 4px solid blue;
}
<div class="block-style">content</div>
  1. width and height is for the content. It doesn't include padding. Notice it's box-sizing related. If box-sizing is border-box, width and height contain padding and border. By default the box-sizing is content-box.
  2. vertical margin has no influence to inline element.
  3. margin defines the space between siblings not parent. But child's margin can transferred to parent. And there's a special situation called margin collapse.

Position model

Properties top, bottom, left, right are to set the position of a css element.

  1. position: relative. The element is positioned relative to its normal position.
  2. position: absolute. The element is positioned to its first non static positioned ancestor.
  3. position: fixed. The element's position is relative to the browser.
  4. left, right, top, bottom are all related to its reference's corresponding edge. eg, left is set the offset to the ancestor's left edge if the position is absolute.