Skip to content

使用flex固定头部和底部中间滚动

Published: at 07:44 AM | 2 min read

使用flex固定头部和底部中间滚动

关键点:

‘100vh’浏览器视口高度的百分比,这里是100%;
flex为1其他元素为0时(默认为0),当有多余空间时会被flex为1的元素侵占;
flexShrink为0,当空间被压缩时flexShrink为0的元素不被压缩;

代码如下:

class App extends React.Component {
  render() {
    const items = [1, 2, 3, 4, 5, 6, 7]
    return (
        <div style={Style.root}>
            <div style={Style.head}>head</div>
            <div style={Style.content}>
                {items.map((item, index) => {
                    return <div key={index} style={Style.item}>{item}</div>
                })}
            </div>
            <div style={Style.footer}>footer</div>
        </div>
    )
  }
}

const Style = {}
Style.root = {
    display: 'flex',
    flexDirection: 'column',
    height: '100vh',
    overflowY: 'hidden'
}

Style.head = {
    height: 80,
    backgroundColor: '#ccc',
}

Style.footer = {
    height: 80,
    backgroundColor: '#ccc',
} 

Style.content = {
    display: 'flex',
    flexDirection: 'column',
    flex: 1, 
    overflowY: 'scroll'
}

Style.item = {
    display: 'flex',
    height: 200,
    flexShrink: 0,
    backgroundColor: 'rgb(232, 128, 36)',
    margin: 10
}

export default App;