Home > Software design >  How to change the placeholder of an input in css?
How to change the placeholder of an input in css?

Time:06-17

I have an input in a form that looks like this: <input type="text" placeholder="My placeholder" value=""> I want to be able to change the placeholder content in css, from "My placeholder" to something else. I managed to change the color and background and the other attributes with the following css snippet, but the content of the placeholder I cannot change. What attribute should I put instead of content ?


::placeholder {
  font-style: italic;
  font-size: 1em;
  color: mintcream;
  background: thistle;
  padding: 5px;
  content : "some other placeholder" !important;
}

CodePudding user response:

You can't change the value of an attribute in CSS but you could use a tricky workaround if your input is inside a form and you can wrap the input.


In short:

  • wrap the input with a <span> element
  • overlap the span::before pseudoelement over the input and apply the style you chose for the :placeholder pseudoclass
  • change the color and background of :placeholder so it's not visible anymore
  • set pointer-events to none for span::before so every click to this element will be ignored and intercepted from the underlying input element.
  • use a required attribute for the input
  • when the form is :valid then hide the pseudolement

span::before,
::placeholder {
  font-family: arial;
  font-style: italic;
  font-size: .75rem;
  padding: 5px;
  line-height: 1;
  box-sizing: border-box;
}

::placeholder {
  color: transparent;
  background: transparent;
}

span {
  position: relative;
}

span::before {
  content : "some other placeholder very long" ;
  position: absolute;
  inset: 0 5px;
  z-index: 1;
  color: mintcream;
  background: thistle;
  width: calc(100% - 10px);
  white-space: nowrap;
  overflow: hidden;
  pointer-events: none;
}

form:valid span::before  {
  display: none;
}
<form>
  <span><input type="text" placeholder="my placeholder" required /></span>
</form>

  • Related