【问题标题】:Position footer on bottom when there is no scrollbar?没有滚动条时将页脚放在底部?
【发布时间】:2012-10-10 00:18:14
【问题描述】:

我有一个包含使用 php 包含函数的元素的 div,下面我有一个页脚。只有滚动到页面底部才能看到页脚,以节省空间。

问题是如果内容高度很小(例如 300px),那么页脚没有放在页面底部,这使得布局看起来不太好。

所以我的问题是,当浏览器窗口上没有出现滚动条时(意味着内容 div 高度很小),我可以将页脚放在底部吗?

【问题讨论】:

    标签: css html position height scrollbar


    【解决方案1】:

    听起来像 sticky footer 就是你要找的东西:

    HTML:

    <div id="wrap">
        <div id="main">content</div>
    </div>
    
    <div id="footer">footer</div>​
    

    CSS:

    * { margin:0; padding:0; } 
    
    html, body, #wrap { height: 100%; }
    
    body > #wrap {
        height: auto; 
        min-height: 100%;
    }
    
    #main { 
        padding-bottom: 40px; /* must be same height as the footer */
    }  
    
    #footer { 
        position: relative;
        margin-top: -40px; /* negative value of footer height */
        height: 40px;
        clear:both;
        background: #c00;
    }
    

    Fiddle here.

    这将允许footer div 至少位于窗口底部;随着 main 内容 div 的增长,它会相应地将页脚向下推。

    【讨论】:

      【解决方案2】:

      这只能通过 JavaScript 来完成,因为您的服务器 (PHP) 无法知道窗口的高度。话虽如此,它当然可以做到:如果内容小于浏览器窗口的高度,你可以例如在页脚 div 上设置 position:fixedbottom: 0px 以将其粘贴到窗口底部;否则,就让它在内容的底部。

      【讨论】:

      • 感谢这项工作:$(document).ready(function() { if (document.getElementById('content').scrollHeight &lt; document.body.clientHeight){ document.getElementById('footer').style.position = "fixed"; document.getElementById('footer').style.bottom = "0"; } }); &lt;/script&gt;
      • 其实我发现了一个问题。内容 div 有一个背景图像。脚本运行后,作为页脚位置的区域现在是空的,并且没有应用背景。有什么想法吗?
      猜你喜欢
      • 2015-08-12
      • 2014-12-24
      • 2014-12-12
      • 2013-12-14
      • 2013-07-27
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      相关资源
      最近更新 更多