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-bottom
is relative width. That is, the entire Wrapper
height is equal to padding-bottom
the height, and Wrapper
there is no content height. How to place the DIV we prepared into it without the content height? The answer is absolute positioning, so there Wrapper
is a position:relative
convenient sub-element in the style Relative to Wrapper
the 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-top
The wrapper
above ::before
pseudo-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