18

I am wanting to add a red asterisk for my required fields. So far I have tried using this:

.required-field::before {
  content: "*";
  color: red;
  float: right;
}
<div class="required-field">Issued By:</div>
<input type="text" id="issuedBy">

But the problem is it keeps putting the asterisk too far right. I want it to be right next to the text "Status:" and "Issued By:". I tried removing the float attribute, but it then places the red asterisk in front of the text.

3 Answers 3

26

Rather than ::before use ::after and remove the float: right.

::before places a pseudoelement before the element you're selecting. ::after will place it after, so rather than putting the asterisk before the element you want and moving it with a float/position you can just place it after naturally.

The reason the asterisk was moved too far to the right is because floating moves the element to the right side of the parent container (not always the parent element, let me know if you want me to elaborate). So by floating right you were telling it to move to the far right of the label container which means just to the left of the text boxes, and not to the right of the label text.

https://jsfiddle.net/h4depmdf/1/

.required-field::after {
    content: "*";
    color: red;
}
6

Hey you are floating the asterisk to right

instead use

.required-field::after {
  content: "*";
  color: red;
  margin-left:2px
}

You are using pseudo ::before selector which is placing the content before the element. Use pseudo ::after to place it after the element.

2

.required-field::before {
  content: "*";
  color: red;
}
<html>
   <form id="nonUsSafety" method="post">
      <div class="divTable">
         <div class="divTableBody">
            <div class="divTableRow">
               <div class="divTableCell">Status:<span class="required-field"></span></div>
               <div class="divTableCell"><input type="text" id="statusNonUs"></div>
            </div>
            <div class="divTableRow">
               <div class="divTableCell">Issued By:<span class="required-field"></span></div>
               <div class="divTableCell"><input type="text" id="issuedBy"></div>
            </div>
         </div>
      </div>
   </form>
</html>

1
  • 1
    Posting code alone does not make for a good answer. Add some words explaining what you changed and why.
    – Don
    Commented Aug 7, 2017 at 18:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.