Statement: How to make a block to have proper height based on the given width and dimensions ratio.
tags: html, css, layout, keep ratio, 4x3, 16x19, aspect, height
| <!doctype html> | |
| <html> | |
| <head> | |
| <meta charset=utf-8> | |
| </head> | |
| <body> | |
| <!-- This guy get its "width" dimension --> | |
| <div class="container-with-dimensions"> | |
| <!-- This guy wraps the main guy - one whos ratio we want to keep --> | |
| <div class="aspect aspect-wrapper"> | |
| <!-- This guy does the magic (stretch parent to the proper height) --> | |
| <div class="ratio-4x3"></div> | |
| <!-- The main guy! Now he has proper width and height --> | |
| <div class="mydiv aspect-content"> | |
| </div> | |
| </div> | |
| </div> | |
| </body> | |
| </html> |
| /* Solution framework */ | |
| .aspect { | |
| &.aspect-wrapper { | |
| width: 100%; | |
| position: relative; | |
| & > .aspect-content { | |
| position: absolute; | |
| left: 0; | |
| right: 0; | |
| top: 0; | |
| bottom: 0; | |
| } | |
| & > .ratio-4x3 { padding-bottom: 75%; } | |
| & > .ratio-1x1 { padding-bottom: 100%; } | |
| & > .ratio-3x2 { padding-bottom: 66.666% } | |
| & > .ratio-16x9 { padding-bottom: 56.25% } | |
| } | |
| } | |
| /* Styles for demo */ | |
| body { | |
| width: 36%; | |
| padding: 0 32%; | |
| } | |
| .container-with-dimensions { | |
| width: 75%; | |
| border: 1px solid yellow; | |
| } | |
| .mydiv { | |
| border: 1px solid red; | |
| } |