HTML
<div class='wrapper'>
<div class='elementContainer'>
This line should start halfway down the yellow box
</div>
</div>
CSS
.wrapper
{
position: relative;
height: 300px;
width: 400px;
background: lightyellow;
border: 1px solid black;
}
.elementContainer
{
position: relative;
height: 200px;
width: 300px;
padding-top: 50%;
background: red;
}
Fiddle example: http://jsfiddle.net/jakelauer/s2ZXV/
In the example above, .elementContainer
has a padding-top of 50%
. This should be calculated based on the parent element's (.wrapper
) height, which means it should come out to 150px
. Instead, it comes out to 200px
. What's going on?
Note: When using relative sizing, ems and rems should be used to size text and dimensions on the page related to text size (i.e. padding around text). This creates a consistent layout based on text size. Otherwise, percentages should be used.
This means the padding is calculated according to the parent element width (it's worth to note that in non flexbox layouts, padding top and bottom are also relative to the width of the containing block).
Margin and Padding in percentages are calculated by the width of the parent element.
An element's padding area is the space between its content and its border. Note: Padding creates extra space within an element. In contrast, margin creates extra space around an element.
The specifications explain why.
<percentage>
The percentage is calculated with respect to the width of the generated box's containing block
50% of 400 is 200.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With