Last active
December 4, 2017 19:39
-
-
Save examinedliving/9e94b412d434eb91505c0615f3b4ea93 to your computer and use it in GitHub Desktop.
Less.css mixin that creates a responsive box to hold image of a particular aspect ratio
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
////** | |
// * @file-name: make-ratio.less | |
// * @description A mixin that creates a box that will size responsively to the aspect ratio of an image at all sizes | |
// * @main make-ratio | |
// * @internal make-ratio-parent, make-ratio-child | |
// * @param {number} @width The Width as a number - This is the width of the aspect ratio, not that of the element, nor a percent | |
// * @param {number} @height The Height as a number - see @width for description required | |
// * @param {string} @child - this is the element that will be directly within the outer element of the ratio - defaults to a - only required for using @main mixin (.make-ratio) | |
// * @example | |
// ```less | |
// // in less file | |
// div { | |
// .make-ratio(16,9,em); | |
// } | |
// // in css output file | |
// div { | |
// @padding:percentage(@height/@width); | |
// display: block; | |
// height: 0; | |
// overflow:hidden; | |
// padding-bottom:56.25%; | |
// position: relative; | |
// | |
// >em{ | |
// border:0; | |
// bottom:0; | |
// height:100%; | |
// left:0; | |
// position: absolute; | |
// top:0; | |
// width:100%; | |
// } | |
// } | |
// ``` | |
// */ | |
// #== make-ratio-parent | |
.make-ratio-parent(@width,@height){ | |
// creates the padding necessary for a constant height element | |
@padding:percentage(@height/@width); | |
display: block; | |
height: 0; | |
overflow:hidden; | |
padding-bottom:@padding; | |
position: relative; | |
} | |
// #== make-ratio-child | |
.make-ratio-child(){ | |
// the child element in all the ratios | |
border:0; | |
bottom:0; | |
height:100%; | |
left:0; | |
position: absolute; | |
top:0; | |
width:100%; | |
} | |
// #== make-ratio | |
// | |
// make-ratio is shorthand for the above two mixins | |
// child element needs to be specified as element and not class or id | |
// | |
.make-ratio(@width,@height,@child:~"a"){ | |
// just in case they forget and accidentally pass a string | |
@child-element:replace(@child,'"',''); | |
.make-ratio-parent(@width,@height); | |
// child-element | |
>@{@child-element} { | |
.make-ratio-child(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment