LoginSignup
3

More than 5 years have passed since last update.

縦横比を維持したボックスを生成するmixin

Last updated at Posted at 2014-12-12

スマートフォンサイトにおいて、画面サイズに左右される事なく同じ縦横比を保ちたい、という場面に出くわしたので、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;
            }
        }
    }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3