Pure css to achieve the div container to maintain the aspect ratio

Description

The following methods can be directly copied to the browser to run, zoom and drag the browser size to see the effect.

1. Use positioning to achieve

<!doctype html>
<html>
<style>
  .wrapper{
    
    
    position : relative;
    background: #ccc;
    width: 10%;
    padding-bottom : 20%;
  }
  .inner{
    
    
    position : absolute;
    top : 0; left : 0; right : 0; bottom : 0;
  }
</style>
<head>
  <body>
    <div class="wrapper">
      <div class="inner">
        这是内容
      </div>
    </div>
  </body>
</html>

The mystery is that padding-bottom:20%it padding-bottomis relative width. That is, the entire Wrapperheight is equal to padding-bottomthe height, and Wrapperthere is no content height. How to place the DIV we prepared into it without the content height? The answer is absolute positioning, so there Wrapperis a position:relativeconvenient sub-element in the style Relative to Wrapperthe left vertex positioning.

Second, use pseudo elements

<!doctype html>
<html>
  <style>
    .wrapper {
    
    
      background: #ccc;
      width: 10%;
    }
    .wrapper::before {
    
    
      content: '';
      padding-top: 200%;
      float: left;
    }
    .wrapper::after {
    
    
      content: '';
      display: block;
      clear: both;
    }
  </style>
<head>
<body>
  <div class="wrapper">
    这是内容
  </div>
</body>
</html>

The method comes from: 30 Seconds of CSS.

padding-topThe wrapperabove ::beforepseudo-element makes the height of the element equal to a percentage of its width. 200%Therefore, the height of the element is always 200%the width, creating a response square. This method also allows the content to be placed inside the element normally.

to sum up

The effect of the two methods is the same, you can try it, adjust the size of the browser window to see that the ratio of the elements remains unchanged.
Personally recommend using method two, which can reduce the nesting of divs. But method one is more compatible

Reference: http://www.fly63.com/article/detial/1291?type=3

Guess you like

Origin blog.csdn.net/qq_29722281/article/details/104928450
Recommended