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`)};
`;