To keep div in ratio might be a problem sometimes.
Here shows 3 ways to keep it.
- apply to the element directly
- apply to its pseudo element
- use a placeholder image (might able to generate by js using canvas)
A Pen by WuChengHan on CodePen.
To keep div in ratio might be a problem sometimes.
Here shows 3 ways to keep it.
A Pen by WuChengHan on CodePen.
| <!-- from http://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css --> | |
| <div class="direct"> | |
| <div class="wrapper"> | |
| <div class="content"> | |
| 16:9 | |
| </div> | |
| </div> | |
| </div> | |
| <br> | |
| <!-- from https://css-tricks.com/snippets/sass/maintain-aspect-ratio-mixin/ --> | |
| <div class="pseudo"> | |
| <div class="content"> | |
| 16:9 | |
| </div> | |
| </div> | |
| <br> | |
| <!-- from myself :) --> | |
| <div class="image"> | |
| <img src="https://upload.wikimedia.org/wikipedia/commons/e/e1/B757_(7518728768).jpg"> | |
| <div class="content"> | |
| 16:9 | |
| </div> | |
| </div> |
| .direct, .pseudo, .image { | |
| width: 10%; | |
| background: gold; | |
| animation: 5s linear rwd infinite alternate; | |
| } | |
| @keyframes rwd { | |
| from { | |
| width: 10%; | |
| } | |
| to { | |
| width: 30%; | |
| } | |
| } | |
| .direct { | |
| position: relative; | |
| } | |
| .direct > .wrapper { | |
| position: relative; | |
| width: 100%; | |
| padding-bottom: 56.25%; | |
| } | |
| .direct > .wrapper > .content { | |
| position: absolute; | |
| top: 0; | |
| bottom: 0; | |
| left: 0; | |
| right: 0; | |
| } | |
| .pseudo { | |
| position: relative; | |
| } | |
| .pseudo:before { | |
| display: block; | |
| content: ""; | |
| width: 100%; | |
| padding-top: 56.25%; | |
| } | |
| .pseudo > .content { | |
| position: absolute; | |
| top: 0; | |
| left: 0; | |
| right: 0; | |
| bottom: 0; | |
| } | |
| .image { | |
| position: relative; | |
| } | |
| .image > img { | |
| position: absolute; | |
| width: 100%; | |
| object-fit: contain; | |
| } | |
| .image > .content { | |
| position: absolute; | |
| top: 0; | |
| left: 0; | |
| right: 0; | |
| bottom: 0; | |
| } |