4
votes

While i do understand the overall CSS box model in theory like padding, border, margin, my understanding is restricted to this individual parts.

I often gets confused how this is actually rendered by the browser. E.g. Like padding is within the border, but how is margin calculated? Is it wrt the box border or with respect to the screen? If we give both left and right margins, what takes higher precedence? If there is a width as well as left/right margins, how does the actual rendering take place like is the width of box made first,then the padding or what is it like?

What difference does a float attribute added to this box with margin make?

2
I think what you should do is read up on this in detail on the W3C website (I am assuming that you only care about the W3C standard). If someone answers these questions, you will have more questions, so its best if you read it yourself. w3.org/TR/CSS2/box.html - mmtauqir

2 Answers

4
votes

The box consists of 4 sizes: outer to inner:

  1. Margin - that's the space from the parent, it stacks with the parent's padding.
  2. Border - that's the border's width, it can be specified with border: or border-width:
  3. Padding - that's the space inside the box, if any content/elements inside that box will be spaced that from its sides.
  4. Width - the actual box's width, may change according to content, 100%, or a fixed width as specified in width: or max-width:

An image for illustration: enter image description here


A floated element takes margin into account, so if you have

#element { margin-left: 100px; float: left; }

it will float left, but will have a 100px margin from the left side.

1
votes

"E.g. Like padding is within the border, but how is margin calculated?"

Study this: http://www.w3.org/TR/css3-box/#margins


"Is it wrt the box border or with respect to the screen?"

The calculation of margins is independent from the border and the screen. The browser calculates the value for the margin separately, and then decides how it's going to be applied (rendered).


"If we give both left and right margins, what takes higher precedence?"

An algorithm is specified here: http://www.w3.org/TR/css3-box/#blockwidth

Could you give a specific example?


"If there is a width as well as left/right margins, how does the actual rendering take place like is the width of box made first,then the padding or what is it like?"

The rendering is almost instantaneous, so what counts is the end result, not the order in which the browser renders the element's properties.


"What difference does a float attribute added to this box with margin make?"

Read here: http://www.w3.org/TR/css3-box/#floating

The used values of the margins are equal to the computed values, except that the used values of any margins computed as ‘auto’ are ‘0’.