Created
March 18, 2020 02:16
-
-
Save mutongwu/897b059d8b090ea379b537a25b8c3fe2 to your computer and use it in GitHub Desktop.
如何让一个div跟图片一样,自适应宽高比例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://codepen.io/aghassemi/pen/RpdaKM | |
<div style="height:320px"> | |
<div class="parent"> | |
<div class="wrapper"> | |
<!-- To change aspect ratio, change SVG's width/height --> | |
<img class="resizer" src='data:image/svg+xml;utf8,<svg height="2px" width="1px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"></svg>'></img> | |
<div class="child">Child maintains aspect ratio as parent's height changes</div> | |
</div> | |
</div> | |
</div> | |
<div style="float:left;"> | |
<h2>How does this work?</h2> | |
<p>`img` can update its width based on its height while mainating the aspect ratio as defined by its intrinsic size. Using an SVG we create an image with intrinsic aspect ratio we want and rely on the browser to resize the width when height changes.</p> | |
</div> | |
<style> | |
.parent { | |
padding: 10px; | |
height: 300px; | |
background: green; | |
animation-name: resize; | |
animation-duration: 4s; | |
animation-iteration-count: infinite; | |
animation-direction: alternate; | |
} | |
.resizer { | |
display: block; | |
min-height:100%; | |
width: auto; | |
height: auto; | |
} | |
.wrapper { | |
display: inline-block; | |
height: 100%; | |
position: relative; | |
/* Chrome bug work-around. | |
* See https://bugs.chromium.org/p/chromium/issues/detail?id=707151 | |
*/ | |
/* padding-right: 0.0001%; */ | |
} | |
.child { | |
position: absolute; | |
top: 0; | |
left: 0; | |
right: 0; | |
bottom: 0; | |
background: red; | |
} | |
@keyframes resize { | |
from {height: 300px;} | |
to {height: 150px;} | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment