使CSS位置属性依赖于窗口大小和平台

时间:2015-04-28 13:27:30

标签: css

我的网页底部有一个页脚。如果用户正在桌面上查看页面,则页脚需要position:fixed;到屏幕底部。但是,根据我的UX规范,在手机或其他小屏幕(宽度小于768px)上查看时,页脚需要

    如果内容短于屏幕高度,则
  • 固定在屏幕底部
  • 如果内容比屏幕更长(更高),则
  • 绝对定位到页面的底部(即内容),因此在滚动之前不可见。这是为了节省宝贵的屏幕空间。

这可以在CSS中完成吗?如果是这样,怎么样? 或者我需要依赖Javascript吗?我们假设页面当前没有使用任何Javascript。

2 个答案:

答案 0 :(得分:4)

首先,如果用户在超过768像素的屏幕上查看网站,您需要始终修复页脚;

这可以通过检测屏幕宽度的媒体查询来实现,并将固定位置应用到页脚,如下所示:

@media(min-width: 768px) {
  footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
  }
}

要解决移动问题,您需要应用我们称之为粘性页脚的内容。这可以使用flexbox

之类的东西轻松完成

考虑以下标记:

<body class="Site">
  <header>…</header>
  <main class="Site-content">…</main>
  <footer>…</footer>
</body>

CSS将是(您可能需要为属性添加前缀)

@media(max-width: 768px) {
  .Site {
    display: flex;
    min-height: 100vh;
    flex-direction: column;
  }

  .Site-content {
    flex: 1 auto 0;
  }
}

答案 1 :(得分:1)

使用css很简单(如果你只是按宽度检测设备)。

首先使用粘性页脚模板开始(注意顶行是可选的):

<div id="wrapper">
    <div class="table">
        <div class="top row"><div class="cell">header</div></div>
        <div class="middle row"><div class="container cell">body</div></div>
        <div class="bottom row"><div class="cell">footer</div></div>
    </div>
</div>

CSS

html, 
body {min-height:100%; padding:0; margin:0;}

#wrapper {position:absolute; top:0; bottom:0; left:0; right:0;}

.table {display:table; width:100%; height:100%;}
.row {display:table-row;}
.cell {display:table-cell;}

这将满足您始终位于页面底部的页脚要求,或者如果内容太大则推迟。我使用了display:table选项,因为它与ie8兼容,但还有很多其他方法可以获得粘性页脚

现在添加媒体查询以修复较大宽度的页脚:

@media screen and (min-width: 768px) {
    .bottom {
        position:fixed; 
        bottom:0; 
        left:0; 
        right:0;
    }
}

Example Fiddle