My weird and wonderful discovery in css

I suppose that for sure this feature is known widely for everybody but up for today’s morning I did not know about it. From https://www.w3.org/TR/CSS2/box.html :
Like margin properties, percentage values for padding properties refer to the width of the generated box’s containing block.
It means that even for ‘padding-top’ and ‘padding-bottom’ :
Percentages: refer to width of containing block but not for it’s height.
And here is beautiful deccision how to Maintain the aspect ratio of a div with CSS . This code was copied from the above link:

<!DOCTYPE html> 
<html> 
    <head> 
        <meta name="viewport" content="width=device-width,  
        initial-scale=1"> 
        <style> 
            .container { 
                background-color: green; 
                position: relative; 
                width: 100%; 
                padding-top: 56.25%; /* 16:9 Aspect Ratio */ 
            } 
  
            .text { 
                position: absolute; 
                top: 0; 
                left: 0; 
                bottom: 0; 
                right: 0; 
                text-align: center; 
                font-size: 25px; 
                color: white; 
            } 
            .example { 
                background: white; 
                color: green; 
                font-weight:bold; 
                font-size: 40px; 
                padding-bottom: 20px; 
            } 
        </style> 
        </head> 
    <body> 
        <div class="container">  
            <div class="text"> 
                <div class = "example">GeeksforGeeks</div> 
                <p>A Computer Science portal for geeks. It  
                contains well written, well thought and well 
                explained computer science and programming  
                articles, quizzes etc. Also it contains several 
                coding questions to practice and develop your  
                skills in programming.</p> 
            </div>  
        </div> 
    </body> 
</html>    

This decision gives us a simple way to responsive images.

.container {
  position: relative;
  width: 100%;
  padding-top: 25%;
  /* 4:1 Aspect Ratio */
}
.text {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  /* background-image: url("../img/banner.jpg"); */
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <div class="container">
      <div class="text" style="background-image: url('../img/banner.jpg');">
      </div>
    </div>
  </body>
</html>

If paradigm of separation of style and content matters – you can put background image into HTML template.

Leave a Reply

Your email address will not be published. Required fields are marked *