Why doesn't Flexbox alignment work on placeholder pseudo-element?

Viewed 480

I'm trying to align the ::placeholder pseudo-element using Flexbox.

I'm aware of traditional ways of alignment, like text-align for inline alignment, the line-height hack for block alignment, or simply absolute positioning. I am not interested in those.

Flexbox works fine for aligning ::before and ::after pseudo-elements (try it!). But somehow it doesn't work for aligning the ::placeholder pseudo-element of <textarea> and <input> elements.

Why?

textarea {
  height: 10rem;
  display: flex;
  /* should put it center center */
  align-items: center;
  justify-content: center;
}

input {
  height: 10rem;
  display: flex;
  /* should put it top center */
  align-items: flex-start;
  justify-content: center;
}
<textarea placeholder="Some text"></textarea>

<input placeholder="Some text" />

3 Answers

Think that flexbox only works when parent have specific width

you can do it with

textarea{
        display: flex;
        width: 400px;
        height: 100px;
        line-height: 100px;
        text-align: center;
    }

or if you want just placeholder to be center use position absolute like this:

    textarea{
        position: relative;
        width: 500px;
        height: 200px;
    }
    textarea::placeholder {
        position: absolute;
        top: 50%;
        right: 35%;
    }

You can horizontally centralize it via text-align and vertically centralize it via line-height.

    textarea {
      height: 10rem;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    textarea::placeholder {
      text-align: center;
      line-height: 10rem;
    }
    <textarea placeholder="I'm not centered"></textarea>

Flexbox works fine for aligning ::before and ::after pseudo-elements (try it!). But somehow it doesn't work for aligning the ::placeholder pseudo-element of <textarea> and <input> elements.

In a flex container, ::before and ::after pseudo-elements are treated as children of the container. Therefore, they are flex items and can accept flex properties.

Note this section from MDN documentation:

In-flow ::after and ::before pseudo-elements are now flex items.

In a flex container, neither the placeholder attribute or ::placeholder pseudo-element can be flex items. Therefore, they ignore flex properties.

Related