Skip to content

Instantly share code, notes, and snippets.

@examinedliving
Last active December 4, 2017 19:39
Show Gist options
  • Save examinedliving/9e94b412d434eb91505c0615f3b4ea93 to your computer and use it in GitHub Desktop.
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
////**
// * @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