position: fixed; でメニューを固定したら親要素からはみ出る問題の対処法
親要素の幅を変数に保存しておき、calc で計算して対処する。
幅の計算
親要素の幅が --outer-width だとする。このとき、max-width を設定することで、幅を親と同じにする。
{
position: fixed;
bottom: 0;
margin: 0 auto;
width: 100%;
max-width: var(--outer-width);
}
left の計算
ウインドウサイズは 100% で取得できるので、計算によって left を設定する。
{
position: fixed;
bottom: 0;
margin: 0 auto;
width: 100%;
max-width: var(--outer-width);
left: calc((100% - var(--outer-width)) * 0.5);
}
スマホ対応
スマホのような max-width 未満スクリーンでは要素が貫通するので、@media で CSS を切り替える。
@media (max-width: 900px) {
.bottom-fixed {
position: fixed;
bottom: 0;
margin: 0 auto;
width: 100%;
max-width: var(--outer-width);
left: 0;
}
}
@media (min-width: 901px) {
.bottom-fixed {
position: fixed;
bottom: 0;
margin: 0 auto;
width: 100%;
max-width: var(--outer-width);
left: calc((100% - var(--outer-width)) * 0.5);
}
}