Why are the padding and margin properties calculated in relation to the width of the parent element?

Asked

Viewed 126 times

7

The declared percentage values are calculated, for the four sides, relative to the width (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:

inserir a descrição da imagem aqui

Child elements have the same class filho, that is, both have the same padding in percentage:

padding-top: 50%;

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

But why the padding and margin properties are calculated in relation to the width of the parent element?

  • 1

    CSS is full of not very smart things. It is defined by committees, where several different people, many of them are not from the area of design, they end up agreeing where each one feels a little, instead of people dedicated to designing it with a dedication and a little more specific knowledge. In this particular case, someone decided that they would have to use a single sense, "so that the margins would be proportional to each other if used horizontally and vertically". But if we get a listing of all the inconsistencies, it pays to open a separate site to deal with the topic.

1 answer

1

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 side to be the same size.
  • If you use a padding-top: 50% will have to be the same size when padding: 50% at the top, then the calculation will also depend on parent width.

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

It seems strange, but this actually facilitates, because the day you have a div with padding: 50% and need to keep only the padding in the top the value will be the same, facilitated so the user of the website.

  • This is why we always use the parent value for the calculation of padding and margin properties, to facilitate maintenance and standardization, so the browser will always know that the calculation and the same independent be the property and padding or padding-top.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.