Setting HTML5 autofocus attribute with CSS

Gene Vincent picture Gene Vincent · Mar 26, 2015 · Viewed 9.8k times · Source

I have a website that has one input field (like a search engine) and I use the HTML5 autofocus attribute on it.

But on very small screen sizes the soft keyboard that pops up on many devices obscures too much of the screen.

Is it possible to se the autofocus attribute in a CSS media query, so its only active on larger displays ?

I know I could set the focus with Javascript, but right now the pages doesn't use any Javascript and I would prefer to avoid it if its possible to use CSS for this.

Answer

cch picture cch · Mar 26, 2015

As suggested above in comments: Use two inputs and make the one hidden (display:none;). Then with a @media rule target screens that have a maximum width of 480px and make the hidden input visible (display:block;) and hide the other one.

CSS:

.smscreen {
  display: none; 
}

@media screen and (max-width: 480px) {
  .lgscreen {
    display: none;
  }

  .smscreen {
    display: block;
  }

}

See Example using CSS.


Otherwise, you can detect the window size with jQuery on page load, and if the screen is larger than 480px to use .focus() function on the input.

See Example using jQuery.