- 要素の幅が100%(= ブラウザの横幅目一杯まで伸ばしている)
- ページが縦に長く、スクロールバーが表示されている
という前提の話。
要素のpositionに”fixed”もしくは”absolute”を設定しているとfancyboxでモーダルウィンドウを表示させたときに幅が横に伸びてしまう。
MEMO
ヘッダーやナビメニューをfixedで固定している場合、モーダルウィンドウの表示と非表示を切り替える度に左右に微妙に動いてしまうのでちょっと気持ち悪い。
理由は以下の通り。
fancyboxでモーダルウィンドウ表示時に要素が横に伸びる理由
- モーダルウィンドウ表示中は、スクロールバーが非表示になる
このとき、スクロールバーの幅を確保するためにbody要素にmargin-rightが設定される(以下の画像参照) - 通常であればmargin-rightのおかげでスクロールバーが非表示であっても要素が横に伸びることはない
- ただし、positionに”fixed”もしくは”absolute”が設定されている要素は親要素(= body要素)のmargin-rightを無視するので、結果としてスクロールバーが非表示になって生じたスペースの分だけ要素が横方向に伸びてしまう。

逆に言えば、そもそもスクロールバーがない(= ページの縦方向が短い)ときはfancyboxのモーダルウィンドウ表示中にmargin-rightが設定されることもないので、positionの値に関わらず要素が横に伸びることはない。
ソースコード
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!-- fancybox --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" /> <script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script> <!-- 略 --> <div class="wrap"> <div class="content content-fixed"> <p>width : 100%, position : fixed</p> <p> -> 横幅が伸びる(bodyのmargin-rightを無視する)</p> </div> <div class="content content-absolute"> <p>width : 100%, position : absolute</p> <p> -> 横幅が伸びる(bodyのmargin-rightを無視する)</p> </div> <div class="content content-relative"> <p>width : 100%, position : relative</p> <p> -> 横幅は変わらない(bodyのmargin-rightが効いている)</p> </div> <div class="content content-static"> <p>width : 100%, position : static</p> <p> -> 横幅は変わらない(bodyのmargin-rightが効いている)</p> </div> <a href="javascript:;" data-src="#fancybox-content" data-fancybox="etc" data-type="inline"> fancyboxコンテンツを表示 </a> </div> <div id="fancybox-content" class="hidden"> <p>fancyboxコンテンツ</p> </div> |
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
.wrap { height: 1000px; /* ページを縦に長くしてスクロールバーを表示させる */ } .content { width: 100%; margin: 20px 0; padding: 20px; } .content-fixed { border: 1px solid #f00; position: fixed; top: 0; } .content-absolute { border: 1px solid #0f0; position: absolute; top:100px; } .content-relative { border: 1px solid #00f; position: relative; margin-top: 220px; } .content-static { border: 1px solid #000; position: static; /* positionの初期値 */ margin-top: 20px; } #fancybox-content { width: 60%; } .hidden { display: none; } .fancybox-bg { opacity: 0.3 !important; /* モーダルの背景色を薄くする */ } |
jQuery
1 2 3 4 5 |
$(function(){ $('[data-fancybox]').fancybox(); }); |
コメントを残す