0

Example with percentage:

.outer {
  display: inline-block;
  outline: 1px solid pink;
}

.inner {
  display: inline-block;
  height: 250px;
  width: 250px;
  background: rgba(255, 255, 0, .5);
  padding: 6.974%;
}
hello
<div class="outer">
  <div class=inner></div>
</div>
world

https://jsfiddle.net/bo3x1cz9/2/ Example with px:

.outer {
  display: inline-block;
  outline: 1px solid pink;
}

.inner {
  display: inline-block;
  height: 250px;
  width: 250px;
  background: rgba(255, 255, 0, .5);
  padding: 17.4222px;
}
hello
<div class="outer">
  <div class=inner></div>
</div>
world

https://jsfiddle.net/v659df4x/

As you can see in the first example, the .outer div does not include the padding in its calculated width when setting the padding of .inner by percentage. The padding is still clearly applied, as can be seen by the yellow square. In both examples, the .inner div has the same size, so why does the .outer div not respect its size when using percentages for padding? It works as expected when using px, as can be seen in the second example.

empiric
  • 7,825
  • 7
  • 37
  • 48
qwerty
  • 5,166
  • 17
  • 56
  • 77
  • 2
    TL;DR from both duplicates: you have a cyclic dependency because percentage of padding require the parent width to be calculated and the parent element is an inline-block so its width depend also on its content (that has the padding) – Temani Afif Jun 14 '21 at 13:41
  • Thanks for clarifying @TemaniAfif it makes sense to me now. Is there a way to do what i'm trying to do? I literally just want a div with a % padding relative to itself. I thought it would work with the wrapper div but as you pointed out that creates a cyclic dependency. Is there a workaround? – qwerty Jun 14 '21 at 13:52
  • *I literally just want a div with a % padding relative to itself* --> mathematically it's impossible because the padding depend on the width and the width depend on the padding – Temani Afif Jun 14 '21 at 14:11
  • You could use JavaScript to calculate the padding that would apply based on the width, and then convert that value to an explicit value such as px or em and then apply that amount. – TylerH Jun 15 '21 at 16:16

0 Answers0