Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does padding percentage work?

Tags:

html

css

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?

like image 339
Jake Avatar asked Oct 15 '13 18:10

Jake


People also ask

Should you use a percentage for padding?

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.

How padding is calculated?

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).

Is padding calculated with width?

Margin and Padding in percentages are calculated by the width of the parent element.

How does padding work in HTML?

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.


1 Answers

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.

like image 99
Explosion Pills Avatar answered Sep 27 '22 17:09

Explosion Pills