cevincheung
V2EX  ›  CSS

前端问题,有时候想做一个页面,典型的上中下三个结构,怎么做刚好让中间的内容居中然后 footer 能始终在屏幕最下方呢?

  •  
  •   cevincheung ·
    cevin · Nov 7, 2015 · 5301 views
    This topic created in 4021 days ago, the information mentioned may be changed or developed.

    [始终] 不是指 fixed.

    10 replies  •  2015-11-07 14:11:28 +08:00
    learnshare
    learnshare
    Nov 7, 2015
    1
    通常不会这么做,因为比较难做到
    (一种方式是禁止浏览器默认的滚动,然后设置子元素可滚动。但这是一种破坏性的处理,会丢失许多浏览器提供的特性)
    loveyu
    loveyu
    Nov 7, 2015 via Android
    2
    据说有两种方式,一种纯 css 实现,需要固定页脚高度,另一种 js 实现。 js 容易太多
    gDD
    gDD
    Nov 7, 2015 via iPhone
    3
    @loveyu 上次看 GitHub 用的第一种。
    FragmentLs
    FragmentLs
    Nov 7, 2015
    4
    <div id="wrapper">
    <header></header>
    <div class="content"></div>
    <footer></footer>
    </div>

    #wrapper {
    min-height: 100%;
    position: relative;
    }

    footer {
    bottom: 0;
    left:0;
    position: absolute;
    }
    Jailecoeu
    Jailecoeu
    Nov 7, 2015 via iPhone
    5
    position:fixed
    NemoAlex
    NemoAlex
    Nov 7, 2015 via iPhone
    7
    1. document 和 body 都 height:100%
    2. 在 body 内建立一个容器,高度也 100%, position: reletive
    3. 在容器内部建立一个 footer ,使用绝对定位固定在底部
    4. 接下来就是垂直居中的部分了,这里有两种情况,内容高度固定,和内容高度未知。固定的话很容易,绝对定位, top:50%, margin-top:-内容高度的一半就可以了
    5. 如果高度未知或者可变,就没有非常优雅的方式了,务实的做法是使用 display: table-cell ,激进的做法是使用新的 flexbox 模型

    手机打不了太多字,这里只提供线索,具体的自己探索一下吧。
    leoli
    leoli
    Nov 7, 2015
    8
    @NemoAlex 4 的话感觉楼主没有那个垂直居中的要求吧。 不过 document , body 的 height : 100%有必要。我更新了下 jsfiddle https://jsfiddle.net/wliyongfeng/tbyhk3ub/1/
    luoway
    luoway
    Nov 7, 2015
    10
    楼主为什么不画个图描述一下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4839 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 02:28 · PVG 10:28 · LAX 18:28 · JFK 21:28
    ♥ Do have faith in what you're doing.