An expanding middle in CSS

前端 未结 3 1964
走了就别回头了
走了就别回头了 2021-01-02 17:49

How would I go about designing a website which has a fixed height header and footer (attached to the top and bottom of the browser window) but an expanding middle. The scrol

3条回答
  •  一整个雨季
    2021-01-02 18:35

    An old question, but flexbox has given us a super easy way to implement this pattern, a familiar variation on the 'Holy Grail' layout:

    body {
      /*set container to vertical (column) flex mode, ensure body is full height*/
      display: flex;
      min-height: 100vh;
      flex-direction: column;
    }
    header, footer {
      /*more or less equivalent to min-height:50px*/
      flex-basis:50px
    }
    header {
      background-color: #7AEE2D;
    }
    main {
      background-color: #EBAE30;
      /*tell main section to expand to fill available space, this is same as flex 1; or flex:1 1 auto;*/
      flex-grow:1;
    }
    footer {
      background-color: #34A4E7;
    }
    header
    main
    footer

    A note about the syntax: I've used the "atomic" flexbox CSS properties here for simplicity, but in the wild you are more likely to run into the shorthand syntax using the flex keyword by itself. The default values for the 3 properties you can set on flex items (children of a display:flex container) are:

    Initial value as each of the properties of the shorthand: flex-grow: 0 flex-shrink: 1 flex-basis: auto

    Using flex, there are multiple ways to compose these properties, specifying one, two, or three values, and those values can by keywords, unit lengths (2px), or unitless grow/shrink ratios 2. Many different "overloads" are available, depending on your arguments.

    For example, flex-basis:50px could've been flex:50px, flex:0 1 50px, and flex-grow:1 could have been flex 1; or flex:1 1 auto;. It's still not as bad as some other CSS shorthands I can think of (position, I'm looking at you). The 'flex' shorthand syntax MDN page has more details.

提交回复
热议问题