For what reason are the padding and margin properties calculated relative to the width of the parent element?

6

Declared values with percentage usage are calculated, for all four sides, relative to the width of the parent element.

See the following HTML:

<div class="pai">
    <div class="filho"></div>
</div>

<div class="pai pai-gordo">
  <div class="filho"></div>
</div>

The following CSS:

.pai {
    display: inline-block;
    width: 100px;
    height: 300px;
    background-color: blue;
    margin-right: 10px;
}

.pai-gordo {
    width: 200px;
}

.filho {
    background-color: red;
    width: 50px;
    height:
    padding-top: 50%;
}

And the result:

The child elements have the same class filho , that is, both have the same padding as a percentage:

padding-top: 50%;

However, the result shows that the child of the pai-gordo element takes up more vertical space than the child of the pai element, because the pai-gordo element is wider and padding-top will be 50% width of the father.

But, for what reason are the padding and margin properties calculated relative to the width of the parent element?

    
asked by anonymous 27.12.2016 / 18:34

1 answer

0

The padding and margin property will always use the width and height of the parent to perform the calculation. Example:

  • If you use a padding: 50% you expect the 4 sides to be the same size.
  • If you use a padding-top: 50% will have to be the same size as padding: 50% at the top, so the calculation will also depend on the width of the parent.

This makes it easy for the developer because he knows the padding-top: 50% and even the value of padding: 50%.

It seems strange, but this actually makes it easier, because the day you have a div with padding: 50% and need to keep only the padding at the top the value will be the same, so facilitated the website maintenance.

  • This is the reason to always use the value of the parent for the calculation of the properties padding and margin, to facilitate the maintenance and standardization, so the browser will always know that the calculation is independent and property is padding or padding- top.
27.12.2016 / 20:10