简体   繁体   中英

Adding a red asterisk to required fields

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.

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;
}

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.

 .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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM