5

I have an input in a form that looks like this: <input type="text" placeholder="My placeholder" class="form-control DataTable--global-filter" 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;
}

2
  • CSS is declarative and influenced heavily on cascading flow, but there are some "event-like" circumstances that allow a very limited control dynamically. Can you be more specific as to when you need to change the placeholder? Ex. if the input gets focus or on blur? Commented Jun 17, 2022 at 11:03
  • potential duplicate of stackoverflow.com/q/18329425/11107541 / stackoverflow.com/q/18329425/11107541 Commented Jun 15 at 22:07

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Is it possible that the placeholder remains visible on clicking inside the input?
@kitten_world sure, see my update
Or... yanno... just set the field to required and use the :focus and the valid pseudo-classes...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.