What's the reason for the asterisk showing up exclusively in specific areas?

As part of my HTML and (S)CSS homework, I created a form. You can view it here: https://codepen.io/quokka-wiki/pen/BavqrQL.

To enhance the labels of required fields, I included the following HTML/SCSS code to add a red asterisk:

<html>
    <!-- ... -->
    <body>
        <!-- ... -->
        <label for="username">Username</label>
        <input type="text" name="username" required />

        <label for="password">Password</label>
        <input type="password" name="password" required />

        <!-- ... -->
        <input type="checkbox" name="tos" required />
        <label for="tos">I agree to sell my soul to the Devil for this app</label>
        
    </body>
</html>

However, the styling only seems to apply to certain elements. Can anyone assist me in troubleshooting or suggest a better CSS selector?


Update:

I'm unsure why the code snippet above isn't working as expected, please refer to the CodePen link for accurate display.

Answer №1

According to the comment above, it seems that your selector is not correct. In your code, the label element comes before the input element and has the required attribute assigned to it. Therefore, using the plus sign "+" in your CSS rule will fail to target the label you intend to style. Instead, if there is a following label (which belongs to a different element), the selector will match and apply styles there.

The initial snippet mirrors your code with a similar selector, resulting in the following label being colored yellow instead of the intended one.

:required + label{background:yellow}
:required + label:after{content:'*';color:red}
<label for="username">Username</label>
<input type="text" name="username" required />

<label for="password">Password</label>
<input type="password" name="password" required />

However, by rearranging the order of the label and input elements, you can see the text appearing below the input element, which may not be the desired layout but demonstrates how the selector now correctly applies styles to the right element.

:required + label{background:yellow}
:required + label:after{content:'*';color:red}
<input type="text" name="username" required />
<label for="username">Username</label>

<input type="password" name="password" required />
<label for="password">Password</label>

If you want to position the pseudo content above the input element, you can experiment with a negative margin as a workaround – although it's not the most elegant solution, it somewhat gets the job done.

:required + label:after{
  content:"*";
  color:red;
  position:relative;
  top:-2.5rem;
  margin:0 0 0 0.5rem;
}

label:before{
  content:attr(for);
  position:relative;
  top:-2.5rem;
  z-index:2;
  text-transform:capitalize;
}

label{display:block}

input{margin:2rem 0 0 0}
<input type="text" name="username" required />
<label for="username"></label>

<input type="password" name="password" required />
<label for="password"></label>

Answer №2

The CSS selector you have chosen, :required + label::after, specifies that the label must immediately follow a required field. This is why it works for the password field, as the label comes after the username input which is marked as required.

If you prefer to maintain the element order, an easy solution would be to assign a class to the labels of the required inputs.

Alternatively, you could use the :has selector with the rule label:has(+ :required)::after. It's worth mentioning that this selector is not currently supported by Firefox, so using a class would be a more reliable option.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary for the paths in an HTML file to be full paths when utilizing Express.static in Node.js?

I have the following files: /public/index.html <!DOCTYPE html> <html> <head> <title>Planner</title> <script src="../codebase/library.js" charset="utf-8"></script> <link hre ...

Exploring the functionalities of scss and minified files within Visual Studio 2017

I have very little knowledge of scss. In our Visual Studio 2017 solution explorer, there is a .scss file called Theme6.scss. When I expand it, I see a file named Theme6.css. Upon expanding that file, two more files are revealed: Theme6.css.map and Theme6. ...

The function getComputedStyle(elem).getPropertyValue('fontSize') returns incorrect values when the font size of the element is specified in em units

My current issue involves trying to obtain the font size of an element in the following manner: getComputedStyle(MyTargetElement , "").getPropertyValue('font-size') The result is coming back as 16px, when it should actually be 14px. W ...

Looking to recreate this style of table using HTML and CSS?

https://i.sstatic.net/nDrxq.png Trying to replicate the layout from this image for my blog, but struggling with the source code. Any suggestions on how to achieve a similar design without using divs within table rows? Looking for a cleaner solution. ...

I am having trouble getting my website to work offline using caching

My cache file is displayed below: CACHE MANIFEST # 2013-11-22 14:38:54735779 CACHE: ../../../../assets/img/background_01.jpg ../../../../assets/img/background_02.jpg ../../../../assets/img/background_03.jpg ../../../../assets/img/datepicker_icon.png .. ...

I am experiencing difficulties with my HTML and CSS code not functioning as I had initially intended

I've been dabbling in HTML and attempting to create my own website, but I'm encountering an issue with the positioning of my <table> tag. It keeps appearing at the bottom of the site, despite my CSS instructions to prevent it. The position ...

Is there a way to update a div element with an image without having to refresh

Currently working on a project for my studies where I am reading the x and y coordinates from a touch pad and drawing it in real time using PHP. I have created a draw page that takes these coordinates and displays them on an image, which is then shown on ...

Empty slots on an HTML form appearing consistently upon each refresh

Although this question has been asked multiple times, I am struggling to find a solution for my particular case. I want to establish a connection with the database ONLY when the submit button is pressed and none of the fields are left blank. However, blank ...

I'm searching for a universal guidebook on creating web page layouts

After 5 years of creating webpages, I have realized that my sites tend to have a nostalgic 1995 internet vibe. Despite being a C# programmer with knowledge in HTML, JavaScript, and CSS, my design skills could use some improvement. Is there a quick referenc ...

Div or box container with a CSS arrow sliced through

Is there a way to transition from a basic square menu to something more complex like this -> view image example Below is the CSS I've been using: .menu { width:50px; height:50px; display:block; background-color:red; overflow:hidden -ms-transform: ...

An issue with Destination-Out Composition in HTML5 Canvas

While working on a canvas, I have encountered an issue with deleting a portion of a curve I have drawn. Specifically, I need to remove the last 25% of the curve after it is complete and keep only the first 75%. However, when attempting to delete the lines ...

Tips for embedding JavaScript and CSS files in a partial view

I am having trouble loading JavaScript and CSS files in a partial view of my page. Can someone please assist me with this? Specifically, I need help loading these three files in the Partial View: <link href="~/AdminTheme/BootstrapJalaliDatePicker/ ...

What could be causing the footer to not show up at the bottom of the page?

I've encountered an issue with my code where the footer appears to be stuck at the bottom of the h2_c div instead of the bottom of the .content div where it should be. I have tried using positioning but it hasn't resolved the problem. Thank You. ...

JQuery restricts input to only allow numbers with a set number of digits, ensuring uniqueness

Can someone assist me in creating a jQuery script that only allows unique numbers with exactly 4 digits in a numeric field? Here is the HTML code: <input type="text" id="registration_number" class="input-sm" name="registration_number" maxlength="6" re ...

Issue with integrating Shuffle.js search functionality with Bootstrap 4 cards

For the past few days, I've been experimenting with integrating Shuffle.js into my cards within Bootstrap 4. My goal is to achieve a visually pleasing shuffling effect when searching/filtering these cards. Below is the HTML structure and JavaScript c ...

What could be causing my background image to vanish or flicker in Bootstrap?

Something unusual is happening with my website. There's a section with a static background image, and as you scroll, a quote and button (which will eventually link to a store) appear on top of it. Previously, this setup was working fine. However, yest ...

Tips on customizing the color of the arrow in an mdc-select dropdown menu?

I'm struggling to modify the default purple color of the dropdown arrow in an mdc-select: https://i.sstatic.net/DdDEv.png None of the sass mixins seem to be effective in making the change. Any suggestions on how this can be achieved? Here are my a ...

Is there a way to extract the visible text from an HTML TextNode without including the HTML tags?

My current challenge involves converting a DOM node and all of its children into plain text markup of a custom design. Utilizing node.childNodes allows me to retrieve a list of all content, which can then be recursively transformed into my desired string f ...

Having trouble with -moz-box-flex not flexing? It works perfectly with (Chrome/Webkit) browsers!

I have been searching for hours to figure out why Firefox is not flexing my page content in HTML/CSS. It's working fine in Chrome, and I've double-checked that each -webkit-box-flex has a corresponding -moz-box-flex. Can anyone point out what I m ...

Converting Temperature between Celsius and Fahrenheit using a Dropdown Menu

I am trying to create a conversion tool using a Select menu. The idea is that the first input box will display the temperature unit selected in the menu, but for some reason it's not working as expected. If I choose Celsius from the menu, then the inp ...