CSS - "The sum of the horizontal components of a block-level element box always equals the width of the parent?"

StackOverflow https://stackoverflow.com/questions/20727997

  •  20-09-2022
  •  | 
  •  

Pregunta

I am reading CSS The Definitive Guide by Eric Meyer. On page 162, it says the following:

Almost as simple is the rule that says that the sum of the horizontal components of a block-level element box in the normal flow always equals the width of the parent.

I find a similar passage in the W3C specification:

The horizontal position and size of a non-floating, block-level element is determined by seven properties: 'margin-left', 'border-left', 'padding-left', 'width', 'padding-right', 'border-right' and 'margin-right'. The sum of these seven is always equal to the 'width' of the parent element.

However, I can think of a very simple case where the above rule does not hold true.

# HTML
<div><p>This is a paragraph.</p></div>

# CSS
div { width: 200px; }
p { width: 300px; }

Obviously I could set overflow to contain the p element. However I just want to know am I interpreting the rule incorrectly?

¿Fue útil?

Solución

You shouldn't read the old specifications of CSS1, except for curiosity, as you can read in the red box on the page you linked. CSS2.1 defines well this situation: in paragraph 10.3.3 you can read that such configuration is called over-constrained, and one horizontal margin is ignored and set to a value in order to make the equality true. The right one will be choose if the writing mode is left to right, otherwise it'll be the left one.

Otros consejos

I think it means that the "sub element at 100% always equals the width of the parent". Obviously if you set the width to anything smaller/bigger it will differ. But it inherits the same width unless specifically set.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top