How can I prevent the browser from scrolling on top of the page when clicking the checkbox?

The problem is this rule:

#ck-button label input {
  position:absolute;
  top:-20px;
}

When you click on a label the browser tries to focus the related input. In your case the checkbox element is lying at the top of the page, even outside the viewport – so Firefox tries to scroll there.

You can solve it like this by adding:

#ck-button label {
  display: block;
  position: relative;
  overflow: hidden;
}

Demo

Try before buy

Alternative

Heisenberg points out a problem in his answer which can occur when using extreme values. Unfortunately the proposed idea has the same quirk as the one shown above.

So an alternative solution is simply to hide the input. The functionality is not affected.

CSS

#ck-button label input {
  display: none;
}

Demo

Try before buy


The answer accepted is not entirely true. Works, but not in all cases.

If you use the common css to hide elements (probably -999em or similar) at the "top" attribute, in this case position:relative has nothing to do because always -999em will be much higher than the viewport.

The answer accepted works fine because the "top" is only -20px . Try to set it a more higher number and you´ll see the problem.

So, the solution is not to set a relative position. I think the correct way is only to set a negative value at left position (not top).

Try it. :)


you could hide your checkbox input like this:

#ck-button label input {
    position:absolute;
    top:+20px;
    visibility: hidden;
}

Tags:

Html

Css