Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making CSS position attribute dependent on window size and platform

Tags:

css

I have a footer that runs across the bottom of my web page. If the user is viewing the page on a desktop, the footer needs to have position:fixed; to the bottom of the screen. However, according to my UX spec, when viewed on a phone or other small screen (width less than 768px), the footer needs to be either

  • fixed to the bottom of the screen if the content is shorter than the height of the screen, or
  • absolute positioned to the bottom of the page (i.e., the content) if the content is longer (taller) than the screen, and therefore invisible until scrolled. This is to save precious screen real-estate.

Can this be done within CSS? If so, how? Or do I need to rely on Javascript? Let's assume that the page is currently not using any Javascript yet.

like image 823
pgblu Avatar asked Jul 28 '26 19:07

pgblu


1 Answers

First of all you need your footer to always be fixed if the user is viewing the website on a screen wider than 768px;

This can be achieved using media queries that detect the screen width and apply fixed position to the footer like this:

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

To solve the mobile issue you need to apply what we call a sticky footer. This can be done easily using something like flexbox

consider the following markup:

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

The CSS will be (you might need to prefix the properties)

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

  .Site-content {
    flex: 1 auto 0;
  }
}
like image 157
Ahmad Alfy Avatar answered Jul 30 '26 10:07

Ahmad Alfy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!