Home > Blockchain >  Why float: CSS property doesn't work in @media queries?
Why float: CSS property doesn't work in @media queries?

Time:03-23

I'm making a footer section where if the screen is wider than 815 pixels, some links will be on the rights side, but when the screen is under 815 pixels, I want them to be centred in a new row.

I've tried doing this with @media queries, as well as searching around for a solution, but haven't found a valid one yet.

My CSS code for now is:

footer {
    padding: 25px;
}

footer #right {
    float: right;
    display: block;
}

@media screen and (max-width: 815px) {
    footer {
        width: 100%;
        text-align: center;
    }
    footer #right {
        float: left;
    }
}
<footer>
<h3>&copy; W<strong>3</strong>S &bull; All Rights Reserved <span id="right"><a href="page/support/help_center.htm">Help Center</a> | <a href="page/support/about.htm">About</a> | <a href="page/blog/blog.htm">Blog</a></span></h3>
</footer>

I have tried using "width: 100%;", "float: center;", and many more, but nothing worked.

Any suggestions?

CodePudding user response:

Use float: none

While I would recommend using display: flex as mentioned in dippas's answer, here is how you would do it using floats.

footer {
    padding: 25px;
}

footer #right {
    float: right;
    display: block;
}

@media screen and (max-width: 815px) {
    footer {
        /*  Unnecessary, since footer normally has display: block 
 which is width: 100% by default */
        /* width: 100%; */
        text-align: center;
    }
    footer #right {
        float: none;
        width: 100%;
    }
}
<footer>
<h3>&copy; W<strong>3</strong>S &bull; All Rights Reserved <span id="right"><a href="page/support/help_center.htm">Help Center</a> | <a href="page/support/about.htm">About</a> | <a href="page/blog/blog.htm">Blog</a></span></h3>
</footer>

Also, using a mobile-first CSS approach to reduce lines of code:

footer {
  text-align: center;
    padding: 25px;
}

footer #right {
  display: block;
}

@media screen and (min-width: 815px) {
  
  footer #right {
    float: right;
  }
}
<footer>
  <h3>&copy; W<strong>3</strong>S &bull; All Rights Reserved <span id="right"><a href="page/support/help_center.htm">Help Center</a> | <a href="page/support/about.htm">About</a> | <a href="page/blog/blog.htm">Blog</a></span></h3>
</footer>

CodePudding user response:

Forget floats, use flexbox, also try using mobile-first approach (min-width)

footer {
  text-align: center;
}

@media screen and (min-width: 816px) {
  footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
<footer>
  <h3>&copy; W<strong>3</strong>S &bull; All Rights Reserved</h3>

  <span id="right">
    <a href="page/support/help_center.htm">Help Center</a> | 
    <a href="page/support/about.htm">About</a> | 
    <a href="page/blog/blog.htm">Blog</a>
  </span>
</footer>

  • Related