Search code examples
csscss-position

CSS positioning question. Please asterisk inside a display block element


The CMS I am using is generating a code like this for forms:

<div class="sf-fieldWrp">
    <label for="Textbox-3">Contact Name</label>
    <input type="text" value="" required="required">
    <p>Your full name please</p>
</div>

Now, I would like to place an asterisk next to the label of the fields that are required. The only identifier for required fields in the code is required="required", unfortunately no classes and no ids, only the required attribute.

Is it possible to place the asterisk right after the label of the field, in this case after Contact Name?

I tired this CSS code and it kinda works but it places the asterisk before the label and the label itself is a block element but I can change that if needed.

label { display: block }
.sf-fieldWrp { position: relative }
input[required="required"] + p::before {
  content: "*";
    color: red;
    position: absolute;
    top: 0;
    left: 0;
    font-size: 1.1rem;
    font-style: normal;
}

Here is how it looks now

As you can see the asterisk shows before the label but I want it to show after the label text (not after the label block element).

How do I keep the label and input in two separate lines and place the asterisk after the label text?


Solution

  • You would be able to use the :has on the parent and add the asterisk using after in the label

    .sf-fieldWrp:has(input[required="required"]) label::after {
      content: '*';
      display: inline-block;
      color: red;
    }
    <div class="sf-fieldWrp">
      <label for="Textbox-3">Contact Name</label>
      <input type="text" value="" required="required">
      <p>Your full name please</p>
    </div>