LoginSignup
2
4

More than 5 years have passed since last update.

モバイルブラウザの height: 100vh の話。

Posted at

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4