to dirprocess: css - height as percentage                        rev 25 jun 2022

Category: CSS

⇒  On this page: how to↓     why↓     links↓

....................................................... 
* Goal: In a fluid (responsive) page we want 
    the height of an element to increase/decrease 
    in proportion to its width.
    i.e., the element to retain its aspect ratio.

* Problem: We can tell percent for width, but not height!

.........................
✶  Then how to do it?

  Use percent padding:

.container {
  width:        100%;
  padding-top:  100%;       /* 1:1 Aspect Ratio */
  position:     relative;   /* If you want text inside of it */
}
/* If you want text inside of the container: */
.text {
  position:     absolute;
  top:          0;
  left:         0;
  bottom:       0;
  right:        0;
}

......................... 
Example ratios:

  // 16:9 Aspect Ratio - divide 9 by 16 = 0.5625
  padding-top: 56.25%; 

  // 4:3 Aspect Ratio - divide 3 by 4 = 0.75
  padding-top: 75%; 

  // 3:2 Aspect Ratio - divide 2 by 3 = 0.6666
  padding-top: 66.66%; 

  // 8:5 Aspect Ratio - divide 5 by 8 = 0.625
  padding-top: 62.5%; 

 
.........................
source:

  https://www.w3schools.com/howto/howto_css_aspect_ratio.asp 



.......................................................
➽  why is it like this? 

  - the width of an element depends on its *parent*; 
        is constrained by its parent.
  - the height of an element depends on its *content*.
        (unless you specify a specific height -- which is
         what we don't want to do in this fluid scenario.)
      So we give it a fluid content with padding percent.

  More:
    https://stackoverflow.com/questions/5657964/css-why-doesn-t-percentage-height-work
    https://stackoverflow.com/questions/7049875/why-doesnt-height-100-work-to-expand-divs-to-the-screen-height
    https://stackoverflow.com/questions/31728022/why-is-percentage-height-not-working-on-my-div/

  Find more:
    https://duckduckgo.com/?q=css+height+as+percentage+of+width



_______________________________________________________
begin 25 jun 2022
-- 0 --