V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Can I use?
http://caniuse.com/
Less
http://lesscss.org
Cool Libraries
Bootstrap from Twitter
Jetstrap
cevincheung
V2EX  ›  CSS

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

  •  
  •   cevincheung ·
    cevin · 2015-11-07 10:41:43 +08:00 · 3979 次点击
    这是一个创建于 3090 天前的主题,其中的信息可能已经有所发展或是发生改变。

    [始终] 不是指 fixed.

    10 条回复    2015-11-07 14:11:28 +08:00
    learnshare
        1
    learnshare  
       2015-11-07 11:02:36 +08:00
    通常不会这么做,因为比较难做到
    (一种方式是禁止浏览器默认的滚动,然后设置子元素可滚动。但这是一种破坏性的处理,会丢失许多浏览器提供的特性)
    loveyu
        2
    loveyu  
       2015-11-07 11:03:05 +08:00 via Android
    据说有两种方式,一种纯 css 实现,需要固定页脚高度,另一种 js 实现。 js 容易太多
    gDD
        3
    gDD  
       2015-11-07 11:05:33 +08:00 via iPhone
    @loveyu 上次看 GitHub 用的第一种。
    FragmentLs
        4
    FragmentLs  
       2015-11-07 11:57:19 +08:00
    <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
        5
    Jailecoeu  
       2015-11-07 13:32:29 +08:00 via iPhone
    position:fixed
    leoli
        6
    leoli  
       2015-11-07 13:40:51 +08:00
    NemoAlex
        7
    NemoAlex  
       2015-11-07 13:41:50 +08:00 via iPhone
    1. document 和 body 都 height:100%
    2. 在 body 内建立一个容器,高度也 100%, position: reletive
    3. 在容器内部建立一个 footer ,使用绝对定位固定在底部
    4. 接下来就是垂直居中的部分了,这里有两种情况,内容高度固定,和内容高度未知。固定的话很容易,绝对定位, top:50%, margin-top:-内容高度的一半就可以了
    5. 如果高度未知或者可变,就没有非常优雅的方式了,务实的做法是使用 display: table-cell ,激进的做法是使用新的 flexbox 模型

    手机打不了太多字,这里只提供线索,具体的自己探索一下吧。
    leoli
        8
    leoli  
       2015-11-07 13:50:01 +08:00
    @NemoAlex 4 的话感觉楼主没有那个垂直居中的要求吧。 不过 document , body 的 height : 100%有必要。我更新了下 jsfiddle https://jsfiddle.net/wliyongfeng/tbyhk3ub/1/
    scarlex
        9
    scarlex  
       2015-11-07 14:01:17 +08:00
    luoway
        10
    luoway  
       2015-11-07 14:11:28 +08:00
    楼主为什么不画个图描述一下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3419 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 12:04 · PVG 20:04 · LAX 05:04 · JFK 08:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.