0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

YouTubeっぽいサイドバーを実装する【CSS】【JavaScript】

Posted at

##したいこと

  • 開閉可能なサイドバー
  • メインのコンテナーはサイドバーにぶつかるまで画面(ブラウザー)に対して左右中央

コード

###HTML

<body>
    <aside class="sidebar">いろいろ</div>
    <div class="container">いろいろ</div>
</body>

###SCSS

$container-width: 1140px;

$sidebar-width-open: 250px;
$sidebar-width-close: 50px;

$main-margin: 10px;

.sidebar {
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;

    &.m-open {
        width: $sidebar-width-open;
    }

    &.m-close {
        width: $sidebar-width-close;
    }
}

.container {
    &.m-open {
        width: $container-width + 2*$main-margin;
        margin: 0 auto;

        @media (max-width: $container-width+2*$sidebar-width-open+2*$main-margin) {
            width: 100%;
            padding-left: $sidebar-width-open + $main-margin;
        }
    }
    
    &.m-close {
        width: $container-width + 2*$main-margin;
        margin: 0 auto;
        
        @media (max-width: $container-width+2*$sidebar-width-close+2*$main-margin) {
            width: 100%;
            padding-left: $sidebar-width-close + $main-margin;
        }
    }
}

要はサイドバーを浮かせて、コンテナーの左にサイドバーの幅分paddingを追加してる

###JavaScript

let layouts = [$('.sidebar'), $('.container')];

$('#menu-button').on('click', () => {
    layouts.forEach(layout => {
        layout.toggleClass('m-open');
        layout.toggleClass('m-close');
    });
});

#menu-buttonをクリックしてサイドバーの幅の大きさを切り替え

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?