height: 100vh;
またはmin-height:100vh;
したい場面というのは多いですがモバイルブラウザでは想定した動きをしてくれません。
原因: なぜheight: 100vh;
が効かないのか。
多くのモバイルブラウザでは
- 描画領域が固定ではない(スクロールなどで可変する)
- vhの基準値は再計算されない
- 描画領域の最大値の高さからvhの基準値を計算する
そのため100vh = 現在の画面の高さ
とは限らないのです。
解決策: resize
に合わせてpx指定する
cssは100vh
で高さ指定をしてresize
をトリガーに高さを変更します。サンプルコードはReact
です。
ContainerWithResize.js
class ContainerWithResize extends React.Component {
state = { appHeight: 0 };
componentDidMount = () => {
this.setState({ appHeight: window.innerHeight });
window.addEventListener('resize', () => {
this.setState({ appHeight: window.innerHeight });
});
};
componentWillUnmount = () => window.removeEventListener('resize');
render() {
const { appHeight } = ;
return (
<Container appHeight={this.state.appHeight}>
{this.props.children}
</Container>
);
}
}
export default ContainerWithResize;
const Container = styled.div`
min-height: ${props => (props.appHeight === 0 ? '100vh' : `${props.appHeight}px`)};
`;