Skip to content
Advertisement

Native date input ignores CSS

I have a problem with native inputs of type date. My case consists of a native form with multiple native inputs of different types (text, number, date, etc.) The application featuring the form has a sticky header which results in the following behaviour:

Whenever the form is submitted and the form validation encounters an invalid input for an input field, the form automatically scrolls so that the affected field shows up at the very top of the browser, while showing the validation error message. This field is obscured by the sticky header.

I solved this problem by using the scroll-margin CSS property for the input fields, which respects the height of the sticky header.

This works great for all input types, except for date input fields.

I was not able to find any official bug reports. Has anyone else encountered this behaviour? If so, how could I fix this, without the use of JQuery?

body {
  max-width: 500px;
  font-family: Roboto, sans-serif;
  line-height: 1.4;
  margin: 0 auto;
  padding: 4rem 1rem;
  font-size: 1.5rem;
}

header {
  position: fixed;
  top: 0;
  left: 0;
  text-align: center;
  color: white;
  width: 100%;
  padding: 1rem;
  background: #1976D2;
}

input[type=text] {
  scroll-margin-top: 150px;
}

input[type=date] {
  scroll-margin-top: 150px;
}

input[type=submit] {
  margin-top: 500px;
}
<header>
  Fixed Header.
</header>

<form>
  <input type="text" required/>
  <br/>
  <input type="date" required/>
  <br/>
  <input type="submit">
</form>

Advertisement

Answer

Who needs javascript when it can be done with a single line of CSS? Just add html { scroll-padding-top: 70px; } 🙂

html {
  scroll-padding-top: 70px;
}

body {
  max-width: 500px;
  font-family: Roboto, sans-serif;
  line-height: 1.4;
  margin: 0 auto;
  padding: 4rem 1rem;
  font-size: 1.5rem;
}

header {
  position: fixed;
  top: 0;
  left: 0;
  text-align: center;
  color: white;
  width: 100%;
  padding: 1rem;
  background: #1976D2;
}

input[type=submit] {
  margin-top: 500px;
}
<header>
  Fixed Header.
</header>

<form>
  <input type="text" required/>
  <br/>
  <input type="date" required/>
  <br/>
  <input type="submit">
</form>

https://jsfiddle.net/m4uxj321/

Advertisement