With the current markup I don't think this is possible with just CSS, but:
This is possible if it's ok to add a label
element after the input - like so:
<div>
<input type="password" name="password" id="password" placeholder=" " />
<label for="password">Password</label>
</div>
The trick here is to use the pseudo class:
From the spec:
Input elements can sometimes show placeholder text as a hint to the
user on what to type in. See, for example, the placeholder attribute
in [HTML5]. The :placeholder-shown pseudo-class matches an input
element that is showing such placeholder text.
The idea here is for the text "Password *" to simulate placeholder text.
Placeholders are always shown on input
elements - even if they are focused - unless a value is set on them.
By using the :placeholder-shown
pseudo class on the input
- we can determine when to display the label text.
This is the key selector:
input:placeholder-shown + label {
display: block;
}
This means: when the input's placeholder is shown - show the "placeholder" label. (otherwise we hide it)
For this reason we still need to set a non-empty placeholder attribute on the input (a simple whitespace is sufficient)
div {
position: relative;
}
label {
position: absolute;
height: 20px;
left: 5px;
top: 0;
bottom: 0;
margin: auto;
display: none;
pointer-events: none;
color: #757575;
font-size: 16px;
font-family: system-ui;
}
label:after {
content: " *";
color: red;
}
input:placeholder-shown + label {
display: block;
}
input {
width: 200px;
border: none;
border-bottom: solid 1px #8d97a0;
padding: 5px;
border-radius: 0;
background: #fff;
box-shadow: none;
height: 20px;
font-size: 16px;
margin: 5px 0;
}
<div>
<input type="password" name="name" id="name" placeholder=" " />
<label for="name">Name</label>
</div>
<div>
<input type="password" name="name" id="name" placeholder="Email" />
</div>
<div>
<input type="password" name="name" id="name" placeholder="Phone" />
</div>
<div>
<input type="password" name="password" id="password" placeholder=" " />
<label for="name">Password</label>
</div>
label
andrequired
in input – Musculature