スマートフォンサイトにおいて、画面サイズに左右される事なく同じ縦横比を保ちたい、という場面に出くわしたので、mixin
にしてみました。
mixin
mixin
// 1:1
@mixin same-ratio-box($width:'100%', $height:'100%') {
position: relative;
width: #{$width};
height: auto;
&:before {
content: '';
display: block;
padding-top: #{$height};
}
> * {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}
e.g.
html
div.box.half
div.box-inner
p ボックス
div.box.origin
div.box-inner
p ボックス
scss
// 2:1
.half {
@include same-ratio-box('100%', '50%');
}
// 画像サイズの縦横比維持
.origin {
@include same-ratio-box('100%', percentage(image-height('origin.png') / image-width('origin.png')));
}
おまけ
mixin
@mixin same-ratio-table($width:'100%', $height:'50%') {
@include same-ratio-box($width,$height);
> * {
// table
> * {
display: table;
width: 100%;
height: 100%;
> * {
display: table-cell;
}
}
}
}