skip to Main Content

I am happy with everything about my scroll to top button on desktop browsers. Where I am struggling is on mobile devices. All I want is to have my button about 20px from the left side when viewing my site on a mobile device. For some weird reason, when I use both chunks of code below, it seems to place the button in the correct place for mobile devices, but the button almost triples in size horizontally. Ideas?

Here is my code for desktop browsing:

#myScrollBtn {
    display: none; /* Hidden by default */
    position: fixed; /* Fixed/sticky position */
    bottom: 20px; /* Place the button at the bottom of the page */
    right: 240px; /* Place the button 240px from the right */
    z-index: 99; /* Make sure it does not overlap */
    border: none; /* Remove borders */
    outline: none; /* Remove outline */
    background-color: #ffa500; /* Set a background color */
    color: white; /* Text color */
    cursor: pointer; /* Add a mouse pointer on hover */
    padding: 15px; /* Some padding */
    border-radius: 10px; /* Rounded corners */
    font-size: 18px; /* Increase font size */
}

#myScrollBtn:hover {
    background-color: #555; /* Add a dark-grey background on hover */
}

And here is the code for mobile devices.

@media (max-width: 800px) {
    { #myScrollBtn { left: 20px; }
}

EDIT: I even tried using right: 1000px or more to bypass this glitch, but it doesn’t move my button far enough to the left where I want it. It won’t move any further left than about 700px no matter how big a number I use.

EDIT2: I finally figured it out and added the answer. If it helps even one person someday, that’d make me happy!

3

Answers


  1. Chosen as BEST ANSWER

    Wow, okay I actually figured it out after messing with it for hours. Hopefully someone else who finds themselves in a similar situation that I was in sees this.

    Also, if someone could explain how it fixed it, I would love that, because although I am happy I figured it out, it goes against my understanding of the margin-right property. The fix was as simple as this:

    @media (max-width: 800px) {
        { #myScrollBtn { margin-right: 75px; }
    }
    

    Shouldn't increasing my right margin have moved the button element to the right?? Again, super happy I got it exactly where I want it now, just a little perplexed as to why it did the trick.


  2. You are applying both a right and left property at the same time which causes it to use both properties to calculate the sizing. Setting right to auto should fix this.

    @media (max-width: 800px) {
      #myScrollBtn {
        left: 20px;
        right: auto;
      }
    }
    
    Login or Signup to reply.
  3. Maybe this will help you (HTML):

    `<head>
    <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-  scale=1.0">
    </head>`
    
    
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search