Jonathan Grant Jonathan Grant - 5 months ago 10
CSS Question

If my math is right this should be centered, right?

From what I read, padding expressed as a % calculates based on the parent container (just like the margin does). So, if that's the case then the 3 elements below should be evenly spaced across the parent div. But, they are not.

If I'm doing my math right, you have the width split up like this:

2% padding left

2% padding right

12% (4% x 3) margin left of all three elements

12% (4% x 3) margin right of all three elements

72% (24% x 3) width of all three elements




100% sum of all the percents, therefore the three elements should be spread evenly.

Am I missing something? Is padding not calculated this way? Is my math wrong?



#parent {
background-color: #F00;
display: block;
overflow: hidden;
margin-right: auto;
margin-left: auto;
max-width: 850px;
padding: 2%;
}
.element {
background-color: #0F0;
display: block;
float: left;
height: 100px;
width: 24%;
margin-left: 4%;
margin-right: 4%;
}

<div id="parent">
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
</div>




Answer

Percentages in width, padding-* and margin-* are resolved relatively to the containing block.

In the case of your .element items, the containing block is the content edge of .parent. Not the padding or margin one, so it does not include the padding: 2% on .parent.

If your .element were for example absolutely positioned (and .parent was relatively positioned), their containing block would be the padding edge of .parent, like you want. Of course, this would take .element completely out of flow and mess your layout.

#parent {
  background-color: #F00;
  display: block;
  overflow: hidden;
  margin-right: auto;
  margin-left: auto;
  max-width: 850px;
  padding: 2%;
  height: 100px;
  position: relative;
}
.element {
  background-color: #0F0;
  position: absolute;
  height: 100px;
  width: 24%;
  left: 06%; /* [[2% + 4%]]+24%+4% + 4%+24%+4% + 4%+24%+4% + 2% */
}
.element + .element {
  left: 38%; /* [[2% + 4%+24%+4% + 4%]]+24%+4% + 4%+24%+4% + 2% */
}
.element + .element + .element {
  left: 70%; /* [[2% + 4%+24%+4% + 4%+24%+4% + 4%]]+24%+4% + 2% */
}
<div id="parent">
  <div class="element"></div>
  <div class="element"></div>
  <div class="element"></div>
</div>

Comments