タイトルの通りですが、祖先要素にtransformが設定されている場合にposition: fixedが効かな苦なるということがあったので、備忘録としてメモ。
サンプルコード
今回やりたかったこととしては、以下のようなモーダル処理の実装になります。
<button id="switch">モーダルを開く</button>
<div class="modal">
<div class="modal-contents">
<p>モーダルの内容です。</p>
</div>
</div>
.modalに対して.is-showを追加・削除することでモーダルを表示できるようにします。
.modal {
display: none;
}
.modal.is-show {
position: fixed;
top: 0;
left: 0;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.4);
}
.modal-contents {
width: 100%;
max-width: 600px;
padding: 50px;
border-radius: 15px;
background: #ffffff;
}
これでモーダルの処理ができたので、モーダル表示のある箇所にスイッチとモーダル内容のセットを配置するようにしていたのですが、祖先要素にtransformが設定されている場合に意図した表示になりませんでした。
<div class="box">
<p>transformを設定した要素内に モーダルのスイッチとモーダル要素を配置</p>
<button id="switch">モーダルを開く</button>
<div class="modal">
<div class="modal-contents">
<p>モーダルの内容です。</p>
</div>
</div>
</div>
.box {
width: 400px;
margin: 30px auto;
transform: translateX(0);
}
position: fixedを指定しているモーダル要素が画面全体に広がらず、transformを設定している.boxを基点とした表示になりました。
transformが祖先要素にある場合のデモページ
解決方法としては祖先要素でtransformを使用しない形に変更するか、transformを指定した要素が祖先要素にならないようにposition: fixedの要素を移動する必要があるようです。
今回の場合はモーダルのスイッチとモーダルの内容をわかりやすいようにセットで配置していただけなので、モーダルの内容のみ.boxの外に移動することで対応できました。
<div class="box">
<p>transformを設定した要素の外にモーダル要素を移動</p>
<button id="switch">モーダルを開く</button>
</div>
<div class="modal">
<div class="modal-contents">
<p>モーダルの内容です。</p>
</div>
</div>
コメントが承認されるまで時間がかかります。