hayley
hayley

Reputation: 406

height in percentage vs padding-bottom in percentage

recently I found an responsive website which changes the image contents in different size of screen. When the screen size is big like desktop computer, the content of the div is like(there is no other text content, just a div filled with an image using background-image):

#div {
    background-image: url('images/pc-content01.jpg');
    background: no-repeat center center;
    height: 1129px;
}

When the screen size gets smaller, the css style changes like:

#div {
    background-image: url('images/pc-content01.jpg');
    background-size: cover;
    height: 0;
    padding-bottom: 95.5%;
}

And the background image will be swap to another image when the screen size is as small as moblie devices.

And my question is, how the percentage of padding-bottom is calculated, why percentage in height is not working but percentage on padding-bottom works? (I understand why percentage on height is not working).

Upvotes: 2

Views: 1170

Answers (3)

Jithin Raj  P R
Jithin Raj P R

Reputation: 6797

Height in percentage

Height using percentage only works if we give height using percentage to the body and html of the page, it will not work otherwise.

Like this-

html, body{
  height:100%;
   background:black;
}

body>div{
 height:50%;
 background:gray;
}
<body>
 <div>HI</div>
</body>

Padding-bottom in percentage

But in the case of percentage on padding-bottom, it works irrespective to the body or HTML. It only checks the width of the containing element.

Like this -

html, body{
   background:black;
}

div{
 background:gray;
 padding-bottom:20%;
}
<body>
<div>HI</div>
</body>

Upvotes: 2

Luuuud
Luuuud

Reputation: 4439

When using a percentage value for paddings, it always refers to the width of the element. See MDN. So in this case the padding-bottom of #div would be 95.5% of its width. When setting percentage value for height it calculates it by using the height of the containing block. See MDN

Upvotes: 2

itacode
itacode

Reputation: 3787

In padding percentages refer to the width of the containing block. In this case is used to maintain the aspect ratio (the image one) when the width changes. It is a trick often used in responsive design. A box with an intrinsic ratio. Percentage in height works differently

The percentage is calculated with respect to the height of the generated box's containing block...

MDN, so is not suitable for that purpose.

Upvotes: 2

Related Questions